Dataset Viewer
Auto-converted to Parquet Duplicate
instance_id
stringlengths
20
32
feedback
stringlengths
5
167
Level
stringclasses
11 values
erroneous_file
stringlengths
21
51
repo
stringclasses
3 values
base_commit
stringlengths
40
40
patch
stringlengths
386
3.07k
test_patch
stringlengths
473
13.9k
problem_statement
stringlengths
262
5.59k
hints_text
stringlengths
0
9.06k
created_at
stringlengths
20
20
version
stringclasses
14 values
FAIL_TO_PASS
stringlengths
52
763
PASS_TO_PASS
stringlengths
2
31.4k
environment_setup_commit
stringlengths
40
40
django__django-15202
Retreival is straightford correct file is the last stacktrace that has valid path
null
django/core/validators.py
django/django
4fd3044ca0135da903a70dfb66992293f529ecf1
diff --git a/django/core/validators.py b/django/core/validators.py --- a/django/core/validators.py +++ b/django/core/validators.py @@ -108,15 +108,16 @@ def __call__(self, value): raise ValidationError(self.message, code=self.code, params={'value': value}) # Then check full URL + try: + splitted_url = urlsplit(value) + except ValueError: + raise ValidationError(self.message, code=self.code, params={'value': value}) try: super().__call__(value) except ValidationError as e: # Trivial case failed. Try for possible IDN domain if value: - try: - scheme, netloc, path, query, fragment = urlsplit(value) - except ValueError: # for example, "Invalid IPv6 URL" - raise ValidationError(self.message, code=self.code, params={'value': value}) + scheme, netloc, path, query, fragment = splitted_url try: netloc = punycode(netloc) # IDN -> ACE except UnicodeError: # invalid domain part @@ -127,7 +128,7 @@ def __call__(self, value): raise else: # Now verify IPv6 in the netloc part - host_match = re.search(r'^\[(.+)\](?::\d{1,5})?$', urlsplit(value).netloc) + host_match = re.search(r'^\[(.+)\](?::\d{1,5})?$', splitted_url.netloc) if host_match: potential_ip = host_match[1] try: @@ -139,7 +140,7 @@ def __call__(self, value): # section 3.1. It's defined to be 255 bytes or less, but this includes # one byte for the length of the name and one byte for the trailing dot # that's used to indicate absolute names in DNS. - if len(urlsplit(value).hostname) > 253: + if splitted_url.hostname is None or len(splitted_url.hostname) > 253: raise ValidationError(self.message, code=self.code, params={'value': value})
diff --git a/tests/forms_tests/field_tests/test_urlfield.py b/tests/forms_tests/field_tests/test_urlfield.py --- a/tests/forms_tests/field_tests/test_urlfield.py +++ b/tests/forms_tests/field_tests/test_urlfield.py @@ -100,6 +100,10 @@ def test_urlfield_clean_invalid(self): # 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:
URLField throws ValueError instead of ValidationError on clean Description forms.URLField( ).clean('////]@N.AN') results in: ValueError: Invalid IPv6 URL Traceback (most recent call last): File "basic_fuzzer.py", line 22, in TestOneInput File "fuzzers.py", line 350, in test_forms_URLField File "django/forms/fields.py", line 151, in clean File "django/forms/fields.py", line 136, in run_validators File "django/core/validators.py", line 130, in __call__ File "urllib/parse.py", line 440, in urlsplit
2021-12-15T15:04:13Z
4.1
["test_urlfield_clean_invalid (forms_tests.field_tests.test_urlfield.URLFieldTest)", "test_urlfield_clean_not_required (forms_tests.field_tests.test_urlfield.URLFieldTest)"]
["test_urlfield_clean (forms_tests.field_tests.test_urlfield.URLFieldTest)", "test_urlfield_clean_required (forms_tests.field_tests.test_urlfield.URLFieldTest)", "test_urlfield_strip_on_none_value (forms_tests.field_tests.test_urlfield.URLFieldTest)", "test_urlfield_unable_to_set_strip_kwarg (forms_tests.field_tests.test_urlfield.URLFieldTest)", "test_urlfield_widget (forms_tests.field_tests.test_urlfield.URLFieldTest)", "test_urlfield_widget_max_min_length (forms_tests.field_tests.test_urlfield.URLFieldTest)"]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django__django-17087
Profile class is withinn many files but each has same neighbor and the neighbor of that neighbour is the actual file
2nd level
django/db/migrations/serializer.py
django/django
4a72da71001f154ea60906a2f74898d32b7322a7
diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py --- a/django/db/migrations/serializer.py +++ b/django/db/migrations/serializer.py @@ -168,7 +168,7 @@ def serialize(self): ): klass = self.value.__self__ module = klass.__module__ - return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), { + return "%s.%s.%s" % (module, klass.__qualname__, self.value.__name__), { "import %s" % module } # Further error checking
diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py --- a/tests/migrations/test_writer.py +++ b/tests/migrations/test_writer.py @@ -211,6 +211,10 @@ class NestedChoices(models.TextChoices): X = "X", "X value" Y = "Y", "Y value" + @classmethod + def method(cls): + return cls.X + def safe_exec(self, string, value=None): d = {} try: @@ -468,6 +472,15 @@ def test_serialize_nested_class(self): ), ) + def test_serialize_nested_class_method(self): + self.assertSerializedResultEqual( + self.NestedChoices.method, + ( + "migrations.test_writer.WriterTests.NestedChoices.method", + {"import migrations.test_writer"}, + ), + ) + def test_serialize_uuid(self): self.assertSerializedEqual(uuid.uuid1()) self.assertSerializedEqual(uuid.uuid4())
Class methods from nested classes cannot be used as Field.default. Description (last modified by Mariusz Felisiak) Given the following model: class Profile(models.Model): class Capability(models.TextChoices): BASIC = ("BASIC", "Basic") PROFESSIONAL = ("PROFESSIONAL", "Professional") @classmethod def default(cls) -> list[str]: return [cls.BASIC] capabilities = ArrayField( models.CharField(choices=Capability.choices, max_length=30, blank=True), null=True, default=Capability.default ) The resulting migration contained the following: # ... migrations.AddField( model_name='profile', name='capabilities', field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, choices=[('BASIC', 'Basic'), ('PROFESSIONAL', 'Professional')], max_length=30), default=appname.models.Capability.default, null=True, size=None), ), # ... As you can see, migrations.AddField is passed as argument "default" a wrong value "appname.models.Capability.default", which leads to an error when trying to migrate. The right value should be "appname.models.Profile.Capability.default".
Thanks for the report. It seems that FunctionTypeSerializer should use __qualname__ instead of __name__: django/db/migrations/serializer.py diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index d88cda6e20..06657ebaab 100644 a b class FunctionTypeSerializer(BaseSerializer): 168168 ): 169169 klass = self.value.__self__ 170170 module = klass.__module__ 171 return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), { 171 return "%s.%s.%s" % (module, klass.__qualname__, self.value.__name__), { 172172 "import %s" % module 173173 } 174174 # Further error checking Would you like to prepare a patch? (regression test is required) Also to nitpick the terminology: Capability is a nested class, not a subclass. (fyi for anyone preparing tests/commit message) Replying to David Sanders: Also to nitpick the terminology: Capability is a nested class, not a subclass. (fyi for anyone preparing tests/commit message) You're right, that was inaccurate. Thanks for having fixed the title Replying to Mariusz Felisiak: Thanks for the report. It seems that FunctionTypeSerializer should use __qualname__ instead of __name__: django/db/migrations/serializer.py diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index d88cda6e20..06657ebaab 100644 a b class FunctionTypeSerializer(BaseSerializer): 168168 ): 169169 klass = self.value.__self__ 170170 module = klass.__module__ 171 return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), { 171 return "%s.%s.%s" % (module, klass.__qualname__, self.value.__name__), { 172172 "import %s" % module 173173 } 174174 # Further error checking Would you like to prepare a patch? (regression test is required) I would be very happy to prepare a patch, i will do my best to write a test that's coherent with the current suite I would be very happy to prepare a patch, i will do my best to write a test that's coherent with the current suite You can check tests in tests.migrations.test_writer.WriterTests, e.g. test_serialize_nested_class().
2023-07-17T20:28:41Z
5.0
["test_serialize_nested_class_method (migrations.test_writer.WriterTests.test_serialize_nested_class_method)"]
["test_args_kwargs_signature (migrations.test_writer.OperationWriterTests.test_args_kwargs_signature)", "test_args_signature (migrations.test_writer.OperationWriterTests.test_args_signature)", "test_empty_signature (migrations.test_writer.OperationWriterTests.test_empty_signature)", "test_expand_args_signature (migrations.test_writer.OperationWriterTests.test_expand_args_signature)", "test_kwargs_signature (migrations.test_writer.OperationWriterTests.test_kwargs_signature)", "test_multiline_args_signature (migrations.test_writer.OperationWriterTests.test_multiline_args_signature)", "test_nested_args_signature (migrations.test_writer.OperationWriterTests.test_nested_args_signature)", "test_nested_operation_expand_args_signature (migrations.test_writer.OperationWriterTests.test_nested_operation_expand_args_signature)", "test_custom_operation (migrations.test_writer.WriterTests.test_custom_operation)", "test_deconstruct_class_arguments (migrations.test_writer.WriterTests.test_deconstruct_class_arguments)", "Test comments at top of file.", "test_migration_path (migrations.test_writer.WriterTests.test_migration_path)", "django.db.models shouldn't be imported if unused.", "test_register_non_serializer (migrations.test_writer.WriterTests.test_register_non_serializer)", "test_register_serializer (migrations.test_writer.WriterTests.test_register_serializer)", "test_serialize_builtin_types (migrations.test_writer.WriterTests.test_serialize_builtin_types)", "test_serialize_builtins (migrations.test_writer.WriterTests.test_serialize_builtins)", "test_serialize_choices (migrations.test_writer.WriterTests.test_serialize_choices)", "Ticket #22943: Test serialization of class-based validators, including", "test_serialize_collections (migrations.test_writer.WriterTests.test_serialize_collections)", "Make sure compiled regex can be serialized.", "test_serialize_complex_func_index (migrations.test_writer.WriterTests.test_serialize_complex_func_index)", "test_serialize_constants (migrations.test_writer.WriterTests.test_serialize_constants)", "test_serialize_datetime (migrations.test_writer.WriterTests.test_serialize_datetime)", "Ticket #22679: makemigrations generates invalid code for (an empty", "test_serialize_enum_flags (migrations.test_writer.WriterTests.test_serialize_enum_flags)", "test_serialize_enums (migrations.test_writer.WriterTests.test_serialize_enums)", "test_serialize_fields (migrations.test_writer.WriterTests.test_serialize_fields)", "test_serialize_frozensets (migrations.test_writer.WriterTests.test_serialize_frozensets)", "test_serialize_functions (migrations.test_writer.WriterTests.test_serialize_functions)", "test_serialize_functools_partial (migrations.test_writer.WriterTests.test_serialize_functools_partial)", "test_serialize_functools_partialmethod (migrations.test_writer.WriterTests.test_serialize_functools_partialmethod)", "test_serialize_iterators (migrations.test_writer.WriterTests.test_serialize_iterators)", "test_serialize_lazy_objects (migrations.test_writer.WriterTests.test_serialize_lazy_objects)", "A reference in a local scope can't be serialized.", "test_serialize_managers (migrations.test_writer.WriterTests.test_serialize_managers)", "test_serialize_multiline_strings (migrations.test_writer.WriterTests.test_serialize_multiline_strings)", "test_serialize_nested_class (migrations.test_writer.WriterTests.test_serialize_nested_class)", "test_serialize_numbers (migrations.test_writer.WriterTests.test_serialize_numbers)", "test_serialize_path_like (migrations.test_writer.WriterTests.test_serialize_path_like)", "test_serialize_pathlib (migrations.test_writer.WriterTests.test_serialize_pathlib)", "test_serialize_range (migrations.test_writer.WriterTests.test_serialize_range)", "test_serialize_set (migrations.test_writer.WriterTests.test_serialize_set)", "test_serialize_settings (migrations.test_writer.WriterTests.test_serialize_settings)", "test_serialize_strings (migrations.test_writer.WriterTests.test_serialize_strings)", "test_serialize_timedelta (migrations.test_writer.WriterTests.test_serialize_timedelta)", "test_serialize_type_model (migrations.test_writer.WriterTests.test_serialize_type_model)", "test_serialize_type_none (migrations.test_writer.WriterTests.test_serialize_type_none)", "An unbound method used within a class body can be serialized.", "test_serialize_uuid (migrations.test_writer.WriterTests.test_serialize_uuid)", "Tests serializing a simple migration.", "test_sorted_dependencies (migrations.test_writer.WriterTests.test_sorted_dependencies)", "#24155 - Tests ordering of imports."]
4a72da71001f154ea60906a2f74898d32b7322a7
django__django-14017
Retreival is straightford correct file is the last stacktrace that has valid path
null
django/db/models/query_utils.py
django/django
466920f6d726eee90d5566e0a9948e92b33a122e
diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -40,7 +40,7 @@ def __init__(self, *args, _connector=None, _negated=False, **kwargs): super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated) def _combine(self, other, conn): - if not isinstance(other, Q): + if not(isinstance(other, Q) or getattr(other, 'conditional', False) is True): raise TypeError(other) # If the other Q() is empty, ignore it and just use `self`.
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -815,6 +815,28 @@ def test_boolean_expression_combined(self): Employee.objects.filter(Exists(is_poc) | Q(salary__lt=15)), [self.example_inc.ceo, self.max], ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__gte=30) & Exists(is_ceo)), + [self.max], + ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__lt=15) | Exists(is_poc)), + [self.example_inc.ceo, self.max], + ) + + def test_boolean_expression_combined_with_empty_Q(self): + is_poc = Company.objects.filter(point_of_contact=OuterRef('pk')) + self.gmbh.point_of_contact = self.max + self.gmbh.save() + tests = [ + Exists(is_poc) & Q(), + Q() & Exists(is_poc), + Exists(is_poc) | Q(), + Q() | Exists(is_poc), + ] + for conditions in tests: + with self.subTest(conditions): + self.assertCountEqual(Employee.objects.filter(conditions), [self.max]) class IterableLookupInnerExpressionsTests(TestCase):
Q(...) & Exists(...) raises a TypeError Description Exists(...) & Q(...) works, but Q(...) & Exists(...) raise a TypeError Here's a minimal example: In [3]: Exists(Product.objects.all()) & Q() Out[3]: <Q: (AND: <django.db.models.expressions.Exists object at 0x7fc18dd0ed90>, (AND: ))> In [4]: Q() & Exists(Product.objects.all()) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-21d3dea0fcb9> in <module> ----> 1 Q() & Exists(Product.objects.all()) ~/Code/venv/ecom/lib/python3.8/site-packages/django/db/models/query_utils.py in __and__(self, other) 90 91 def __and__(self, other): ---> 92 return self._combine(other, self.AND) 93 94 def __invert__(self): ~/Code/venv/ecom/lib/python3.8/site-packages/django/db/models/query_utils.py in _combine(self, other, conn) 71 def _combine(self, other, conn): 72 if not isinstance(other, Q): ---> 73 raise TypeError(other) 74 75 # If the other Q() is empty, ignore it and just use `self`. TypeError: <django.db.models.expressions.Exists object at 0x7fc18dd21400> The & (and |) operators should be commutative on Q-Exists pairs, but it's not I think there's a missing definition of __rand__ somewhere.
Reproduced on 3.1.6. The exception is raised by this two lines in the Q._combine, which are not present in the Combinable._combine from which Exists inherit. if not isinstance(other, Q): raise TypeError(other) Tests: diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index 08ea0a51d3..20d0404f44 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -815,6 +815,15 @@ class BasicExpressionsTests(TestCase): Employee.objects.filter(Exists(is_poc) | Q(salary__lt=15)), [self.example_inc.ceo, self.max], ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__gte=30) & Exists(is_ceo)), + [self.max], + ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__lt=15) | Exists(is_poc)), + [self.example_inc.ceo, self.max], + ) + class IterableLookupInnerExpressionsTests(TestCase): ​PR
2021-02-18T13:05:27Z
4.0
["test_boolean_expression_combined (expressions.tests.BasicExpressionsTests)", "test_boolean_expression_combined_with_empty_Q (expressions.tests.BasicExpressionsTests)"]
["test_resolve_output_field (expressions.tests.CombinedExpressionTests)", "test_deconstruct (expressions.tests.FTests)", "test_deepcopy (expressions.tests.FTests)", "test_equal (expressions.tests.FTests)", "test_hash (expressions.tests.FTests)", "test_not_equal_Value (expressions.tests.FTests)", "test_and (expressions.tests.CombinableTests)", "test_negation (expressions.tests.CombinableTests)", "test_or (expressions.tests.CombinableTests)", "test_reversed_and (expressions.tests.CombinableTests)", "test_reversed_or (expressions.tests.CombinableTests)", "test_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_non_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_aggregates (expressions.tests.ReprTests)", "test_distinct_aggregates (expressions.tests.ReprTests)", "test_expressions (expressions.tests.ReprTests)", "test_filtered_aggregates (expressions.tests.ReprTests)", "test_functions (expressions.tests.ReprTests)", "test_optimizations (expressions.tests.ExistsTests)", "test_equal (expressions.tests.SimpleExpressionTests)", "test_hash (expressions.tests.SimpleExpressionTests)", "test_month_aggregation (expressions.tests.FieldTransformTests)", "test_multiple_transforms_in_values (expressions.tests.FieldTransformTests)", "test_transform_in_values (expressions.tests.FieldTransformTests)", "Complex expressions of different connection types are possible.", "We can fill a value in all objects with an other value of the", "We can filter for objects, where a value is not equals the value", "We can increment a value of all objects in a query set.", "test_compile_unresolved (expressions.tests.ValueTests)", "test_deconstruct (expressions.tests.ValueTests)", "test_deconstruct_output_field (expressions.tests.ValueTests)", "test_equal (expressions.tests.ValueTests)", "test_equal_output_field (expressions.tests.ValueTests)", "test_hash (expressions.tests.ValueTests)", "test_raise_empty_expressionlist (expressions.tests.ValueTests)", "test_resolve_output_field (expressions.tests.ValueTests)", "test_resolve_output_field_failure (expressions.tests.ValueTests)", "test_update_TimeField_using_Value (expressions.tests.ValueTests)", "test_update_UUIDField_using_Value (expressions.tests.ValueTests)", "test_F_reuse (expressions.tests.ExpressionsTests)", "Special characters (e.g. %, _ and \\) stored in database are", "This tests that SQL injection isn't possible using compilation of", "test_expressions_in_lookups_join_choice (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_datetimes (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_range_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_range_lookup_namedtuple (expressions.tests.IterableLookupInnerExpressionsTests)", "test_lefthand_addition (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_and (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_left_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_or (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_right_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_xor (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_xor_null (expressions.tests.ExpressionOperatorTests)", "test_lefthand_division (expressions.tests.ExpressionOperatorTests)", "test_lefthand_modulo (expressions.tests.ExpressionOperatorTests)", "test_lefthand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_lefthand_power (expressions.tests.ExpressionOperatorTests)", "test_lefthand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_lefthand_transformed_field_bitwise_or (expressions.tests.ExpressionOperatorTests)", "test_right_hand_addition (expressions.tests.ExpressionOperatorTests)", "test_right_hand_division (expressions.tests.ExpressionOperatorTests)", "test_right_hand_modulo (expressions.tests.ExpressionOperatorTests)", "test_right_hand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_right_hand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_righthand_power (expressions.tests.ExpressionOperatorTests)", "test_date_case_subtraction (expressions.tests.FTimeDeltaTests)", "test_date_comparison (expressions.tests.FTimeDeltaTests)", "test_date_minus_duration (expressions.tests.FTimeDeltaTests)", "test_date_subquery_subtraction (expressions.tests.FTimeDeltaTests)", "test_date_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subquery_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction_microseconds (expressions.tests.FTimeDeltaTests)", "test_delta_add (expressions.tests.FTimeDeltaTests)", "test_delta_subtract (expressions.tests.FTimeDeltaTests)", "test_delta_update (expressions.tests.FTimeDeltaTests)", "test_duration_expressions (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime_microseconds (expressions.tests.FTimeDeltaTests)", "test_durationfield_add (expressions.tests.FTimeDeltaTests)", "test_exclude (expressions.tests.FTimeDeltaTests)", "test_invalid_operator (expressions.tests.FTimeDeltaTests)", "test_mixed_comparisons2 (expressions.tests.FTimeDeltaTests)", "test_multiple_query_compilation (expressions.tests.FTimeDeltaTests)", "test_negative_timedelta_update (expressions.tests.FTimeDeltaTests)", "test_query_clone (expressions.tests.FTimeDeltaTests)", "test_time_subquery_subtraction (expressions.tests.FTimeDeltaTests)", "test_time_subtraction (expressions.tests.FTimeDeltaTests)", "test_aggregate_rawsql_annotation (expressions.tests.BasicExpressionsTests)", "test_aggregate_subquery_annotation (expressions.tests.BasicExpressionsTests)", "test_annotate_values_aggregate (expressions.tests.BasicExpressionsTests)", "test_annotate_values_count (expressions.tests.BasicExpressionsTests)", "test_annotate_values_filter (expressions.tests.BasicExpressionsTests)", "test_annotation_with_nested_outerref (expressions.tests.BasicExpressionsTests)", "test_annotation_with_outerref (expressions.tests.BasicExpressionsTests)", "test_annotations_within_subquery (expressions.tests.BasicExpressionsTests)", "test_arithmetic (expressions.tests.BasicExpressionsTests)", "test_case_in_filter_if_boolean_output_field (expressions.tests.BasicExpressionsTests)", "test_exist_single_field_output_field (expressions.tests.BasicExpressionsTests)", "test_exists_in_filter (expressions.tests.BasicExpressionsTests)", "test_explicit_output_field (expressions.tests.BasicExpressionsTests)", "test_filter_inter_attribute (expressions.tests.BasicExpressionsTests)", "test_filter_with_join (expressions.tests.BasicExpressionsTests)", "test_filtering_on_annotate_that_uses_q (expressions.tests.BasicExpressionsTests)", "test_filtering_on_q_that_is_boolean (expressions.tests.BasicExpressionsTests)", "test_filtering_on_rawsql_that_is_boolean (expressions.tests.BasicExpressionsTests)", "test_in_subquery (expressions.tests.BasicExpressionsTests)", "test_incorrect_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_incorrect_joined_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_nested_outerref_with_function (expressions.tests.BasicExpressionsTests)", "test_nested_subquery (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_join_outer_ref (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_2 (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_with_autofield (expressions.tests.BasicExpressionsTests)", "test_new_object_create (expressions.tests.BasicExpressionsTests)", "test_new_object_save (expressions.tests.BasicExpressionsTests)", "test_object_create_with_aggregate (expressions.tests.BasicExpressionsTests)", "test_object_update (expressions.tests.BasicExpressionsTests)", "test_object_update_fk (expressions.tests.BasicExpressionsTests)", "test_object_update_unsaved_objects (expressions.tests.BasicExpressionsTests)", "test_order_by_exists (expressions.tests.BasicExpressionsTests)", "test_order_by_multiline_sql (expressions.tests.BasicExpressionsTests)", "test_order_of_operations (expressions.tests.BasicExpressionsTests)", "test_outerref (expressions.tests.BasicExpressionsTests)", "test_outerref_mixed_case_table_name (expressions.tests.BasicExpressionsTests)", "test_outerref_with_operator (expressions.tests.BasicExpressionsTests)", "test_parenthesis_priority (expressions.tests.BasicExpressionsTests)", "test_pickle_expression (expressions.tests.BasicExpressionsTests)", "test_subquery (expressions.tests.BasicExpressionsTests)", "test_subquery_eq (expressions.tests.BasicExpressionsTests)", "test_subquery_filter_by_aggregate (expressions.tests.BasicExpressionsTests)", "test_subquery_filter_by_lazy (expressions.tests.BasicExpressionsTests)", "test_subquery_group_by_outerref_in_filter (expressions.tests.BasicExpressionsTests)", "test_subquery_in_filter (expressions.tests.BasicExpressionsTests)", "test_subquery_references_joined_table_twice (expressions.tests.BasicExpressionsTests)", "test_ticket_11722_iexact_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_16731_startswith_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_chained_filters (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_join_reuse (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering_2 (expressions.tests.BasicExpressionsTests)", "test_update (expressions.tests.BasicExpressionsTests)", "test_update_inherited_field_value (expressions.tests.BasicExpressionsTests)", "test_update_with_fk (expressions.tests.BasicExpressionsTests)", "test_update_with_none (expressions.tests.BasicExpressionsTests)", "test_uuid_pk_subquery (expressions.tests.BasicExpressionsTests)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-11422
manage.py has only one neigbour __init__. but next posisbke file was runserver according to description then it was able t find it using first neighbour
1st Level
django/utils/autoreload.py
django/django
df46b329e0900e9e4dc1d60816c1dce6dfc1094e
diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py --- a/django/utils/autoreload.py +++ b/django/utils/autoreload.py @@ -114,7 +114,15 @@ def iter_modules_and_files(modules, extra_files): # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects # are added to sys.modules, however they are types not modules and so # cause issues here. - if not isinstance(module, ModuleType) or getattr(module, '__spec__', None) is None: + if not isinstance(module, ModuleType): + continue + if module.__name__ == '__main__': + # __main__ (usually manage.py) doesn't always have a __spec__ set. + # Handle this by falling back to using __file__, resolved below. + # See https://docs.python.org/reference/import.html#main-spec + sys_file_paths.append(module.__file__) + continue + if getattr(module, '__spec__', None) is None: continue spec = module.__spec__ # Modules could be loaded from places without a concrete location. If
diff --git a/tests/utils_tests/test_autoreload.py b/tests/utils_tests/test_autoreload.py --- a/tests/utils_tests/test_autoreload.py +++ b/tests/utils_tests/test_autoreload.py @@ -132,6 +132,10 @@ def test_module_without_spec(self): del module.__spec__ self.assertEqual(autoreload.iter_modules_and_files((module,), frozenset()), frozenset()) + def test_main_module_is_resolved(self): + main_module = sys.modules['__main__'] + self.assertFileFound(Path(main_module.__file__)) + class TestCommonRoots(SimpleTestCase): def test_common_roots(self):
Autoreloader with StatReloader doesn't track changes in manage.py. Description (last modified by Mariusz Felisiak) This is a bit convoluted, but here we go. Environment (OSX 10.11): $ python -V Python 3.6.2 $ pip -V pip 19.1.1 $ pip install Django==2.2.1 Steps to reproduce: Run a server python manage.py runserver Edit the manage.py file, e.g. add print(): def main(): print('sth') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ticket_30479.settings') ... Under 2.1.8 (and prior), this will trigger the auto-reloading mechanism. Under 2.2.1, it won't. As far as I can tell from the django.utils.autoreload log lines, it never sees the manage.py itself.
Thanks for the report. I simplified scenario. Regression in c8720e7696ca41f3262d5369365cc1bd72a216ca. Reproduced at 8d010f39869f107820421631111417298d1c5bb9. Argh. I guess this is because manage.py isn't showing up in the sys.modules. I'm not sure I remember any specific manage.py handling in the old implementation, so I'm not sure how it used to work, but I should be able to fix this pretty easily. Done a touch of debugging: iter_modules_and_files is where it gets lost. Specifically, it ends up in there twice: (<module '__future__' from '/../lib/python3.6/__future__.py'>, <module '__main__' from 'manage.py'>, <module '__main__' from 'manage.py'>, ...,) But getattr(module, "__spec__", None) is None is True so it continues onwards. I thought I managed to get one of them to have a __spec__ attr but no has_location, but I can't seem to get that again (stepping around with pdb) Digging into wtf __spec__ is None: ​Here's the py3 docs on it, which helpfully mentions that ​The one exception is __main__, where __spec__ is set to None in some cases Tom, will you have time to work on this in the next few days? I'm sorry for assigning it to myself Mariusz, I intended to work on it on Tuesday but work overtook me and now I am travelling for a wedding this weekend. So I doubt it I'm afraid. It seems Keryn's debugging is a great help, it should be somewhat simple to add special case handling for __main__, while __spec__ is None we can still get the filename and watch on that. np, Tom, thanks for info. Keryn, it looks that you've already made most of the work. Would you like to prepare a patch?
2019-05-27T19:15:21Z
3.0
["test_main_module_is_resolved (utils_tests.test_autoreload.TestIterModulesAndFiles)"]
["test_watchman_available (utils_tests.test_autoreload.GetReloaderTests)", "test_watchman_unavailable (utils_tests.test_autoreload.GetReloaderTests)", "test_calls_start_django (utils_tests.test_autoreload.RunWithReloaderTests)", "test_calls_sys_exit (utils_tests.test_autoreload.RunWithReloaderTests)", "test_swallows_keyboard_interrupt (utils_tests.test_autoreload.RunWithReloaderTests)", "test_common_roots (utils_tests.test_autoreload.TestCommonRoots)", "test_no_exception (utils_tests.test_autoreload.TestRaiseLastException)", "test_raises_exception (utils_tests.test_autoreload.TestRaiseLastException)", "test_mutates_error_files (utils_tests.test_autoreload.TestCheckErrors)", "test_sys_paths_absolute (utils_tests.test_autoreload.TestSysPathDirectories)", "test_sys_paths_directories (utils_tests.test_autoreload.TestSysPathDirectories)", "test_sys_paths_non_existing (utils_tests.test_autoreload.TestSysPathDirectories)", "test_sys_paths_with_directories (utils_tests.test_autoreload.TestSysPathDirectories)", "test_manage_py (utils_tests.test_autoreload.RestartWithReloaderTests)", "test_python_m_django (utils_tests.test_autoreload.RestartWithReloaderTests)", "test_run_loop_catches_stopiteration (utils_tests.test_autoreload.BaseReloaderTests)", "test_run_loop_stop_and_return (utils_tests.test_autoreload.BaseReloaderTests)", "test_wait_for_apps_ready_checks_for_exception (utils_tests.test_autoreload.BaseReloaderTests)", "test_wait_for_apps_ready_without_exception (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_files_with_recursive_glob (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_with_glob (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_with_single_file (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_without_absolute (utils_tests.test_autoreload.BaseReloaderTests)", "test_file (utils_tests.test_autoreload.StatReloaderTests)", "test_glob (utils_tests.test_autoreload.StatReloaderTests)", "test_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)", "test_multiple_globs (utils_tests.test_autoreload.StatReloaderTests)", "test_multiple_recursive_globs (utils_tests.test_autoreload.StatReloaderTests)", "test_nested_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)", "test_overlapping_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)", "test_overlapping_globs (utils_tests.test_autoreload.StatReloaderTests)", "test_snapshot_files_ignores_missing_files (utils_tests.test_autoreload.StatReloaderTests)", "test_snapshot_files_updates (utils_tests.test_autoreload.StatReloaderTests)", "test_snapshot_files_with_duplicates (utils_tests.test_autoreload.StatReloaderTests)", "test_check_errors_called (utils_tests.test_autoreload.StartDjangoTests)", "test_echo_on_called (utils_tests.test_autoreload.StartDjangoTests)", "test_starts_thread_with_args (utils_tests.test_autoreload.StartDjangoTests)", "test_watchman_becomes_unavailable (utils_tests.test_autoreload.StartDjangoTests)", ".pyc and .pyo files are included in the files list.", "test_check_errors (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_check_errors_catches_all_exceptions (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_file_added (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_module_without_spec (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_paths_are_pathlib_instances (utils_tests.test_autoreload.TestIterModulesAndFiles)", "iter_all_python_module_file() ignores weakref modules.", "test_zip_reload (utils_tests.test_autoreload.TestIterModulesAndFiles)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django__django-14915
2 files related to given function name
1
django/forms/models.py
django/django
903aaa35e5ceaa33bfc9b19b7f6da65ce5a91dd4
diff --git a/django/forms/models.py b/django/forms/models.py --- a/django/forms/models.py +++ b/django/forms/models.py @@ -1166,6 +1166,9 @@ def __init__(self, value, instance): def __str__(self): return str(self.value) + def __hash__(self): + return hash(self.value) + def __eq__(self, other): if isinstance(other, ModelChoiceIteratorValue): other = other.value
diff --git a/tests/model_forms/test_modelchoicefield.py b/tests/model_forms/test_modelchoicefield.py --- a/tests/model_forms/test_modelchoicefield.py +++ b/tests/model_forms/test_modelchoicefield.py @@ -2,7 +2,7 @@ from django import forms from django.core.exceptions import ValidationError -from django.forms.models import ModelChoiceIterator +from django.forms.models import ModelChoiceIterator, ModelChoiceIteratorValue from django.forms.widgets import CheckboxSelectMultiple from django.template import Context, Template from django.test import TestCase @@ -341,6 +341,12 @@ class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField): </div>""" % (self.c1.pk, self.c2.pk, self.c3.pk), ) + def test_choice_value_hash(self): + value_1 = ModelChoiceIteratorValue(self.c1.pk, self.c1) + value_2 = ModelChoiceIteratorValue(self.c2.pk, self.c2) + self.assertEqual(hash(value_1), hash(ModelChoiceIteratorValue(self.c1.pk, None))) + self.assertNotEqual(hash(value_1), hash(value_2)) + def test_choices_not_fetched_when_not_rendering(self): with self.assertNumQueries(1): field = forms.ModelChoiceField(Category.objects.order_by('-name'))
ModelChoiceIteratorValue is not hashable. Description Recently I migrated from Django 3.0 to Django 3.1. In my code, I add custom data-* attributes to the select widget options. After the upgrade some of those options broke. Error is {TypeError}unhashable type: 'ModelChoiceIteratorValue'. Example (this one breaks): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): context = super().create_option(name, value, label, selected, index, subindex, attrs) if not value: return context if value in self.show_fields: # This is a dict {1: ['first_name', 'last_name']} context['attrs']['data-fields'] = json.dumps(self.show_fields[value]) However, working with arrays is not an issue: def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): context = super().create_option(name, value, label, selected, index, subindex, attrs) if not value: return context if value in allowed_values: # This is an array [1, 2] ...
Thanks for the ticket. Agreed, we could make ModelChoiceIteratorValue hashable by adding: def __hash__(self): return hash(self.value) For now you can use value.value as ​documented in the "Backwards incompatible changes in 3.1" section. Would you like to prepare a patch? Replying to Mariusz Felisiak: Thanks for the ticket. Agreed, we could make ModelChoiceIteratorValue hashable by adding: def __hash__(self): return hash(self.value) For now you can use value.value as ​documented in the "Backwards incompatible changes in 3.1" section. Would you like to prepare a patch? Yes, sure. Patch: ​https://github.com/django/django/pull/14915
2021-09-29T22:00:15Z
4.1
["test_choice_value_hash (model_forms.test_modelchoicefield.ModelChoiceFieldTests)"]
["test_basics (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choice_iterator_passes_model_to_widget (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices_bool (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices_bool_empty_label (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices_freshness (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices_not_fetched_when_not_rendering (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices_radio_blank (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_clean_model_instance (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_clean_to_field_name (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_custom_choice_iterator_passes_model_to_widget (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_deepcopies_widget (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_disabled_modelchoicefield (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_disabled_modelchoicefield_has_changed (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_disabled_modelchoicefield_initial_model_instance (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_disabled_modelmultiplechoicefield_has_changed (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_disabled_multiplemodelchoicefield (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "ModelChoiceField with RadioSelect widget doesn't produce unnecessary", "Widgets that render multiple subwidgets shouldn't make more than one", "Iterator defaults to ModelChoiceIterator and can be overridden with", "test_queryset_manager (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_queryset_none (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_result_cache_not_shared (model_forms.test_modelchoicefield.ModelChoiceFieldTests)"]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django__django-15996
Need to identify EnumSerializer as a function or a class
Level 0
django/db/migrations/serializer.py
django/django
b30c0081d4d8a31ab7dc7f72a4c7099af606ef29
diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py --- a/django/db/migrations/serializer.py +++ b/django/db/migrations/serializer.py @@ -16,7 +16,7 @@ from django.db.migrations.operations.base import Operation from django.db.migrations.utils import COMPILED_REGEX_TYPE, RegexObject from django.utils.functional import LazyObject, Promise -from django.utils.version import get_docs_version +from django.utils.version import PY311, get_docs_version class BaseSerializer: @@ -125,8 +125,21 @@ class EnumSerializer(BaseSerializer): def serialize(self): enum_class = self.value.__class__ module = enum_class.__module__ + if issubclass(enum_class, enum.Flag): + if PY311: + members = list(self.value) + else: + members, _ = enum._decompose(enum_class, self.value) + members = reversed(members) + else: + members = (self.value,) return ( - "%s.%s[%r]" % (module, enum_class.__qualname__, self.value.name), + " | ".join( + [ + f"{module}.{enum_class.__qualname__}[{item.name!r}]" + for item in members + ] + ), {"import %s" % module}, )
diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py --- a/tests/migrations/test_writer.py +++ b/tests/migrations/test_writer.py @@ -413,6 +413,14 @@ def test_serialize_enum_flags(self): "(2, migrations.test_writer.IntFlagEnum['B'])], " "default=migrations.test_writer.IntFlagEnum['A'])", ) + self.assertSerializedResultEqual( + IntFlagEnum.A | IntFlagEnum.B, + ( + "migrations.test_writer.IntFlagEnum['A'] | " + "migrations.test_writer.IntFlagEnum['B']", + {"import migrations.test_writer"}, + ), + ) def test_serialize_choices(self): class TextChoices(models.TextChoices):
Support for serialization of combination of Enum flags. Description (last modified by Willem Van Onsem) If we work with a field: regex_flags = models.IntegerField(default=re.UNICODE | re.IGNORECASE) This is turned into a migration with: default=re.RegexFlag[None] This is due to the fact that the EnumSerializer aims to work with the .name of the item, but if there is no single item for the given value, then there is no such name. In that case, we can use enum._decompose to obtain a list of names, and create an expression to create the enum value by "ORing" the items together.
patch of the EnumSerializer
2022-08-25T04:49:14Z
4.2
["test_serialize_enum_flags (migrations.test_writer.WriterTests)"]
["test_args_kwargs_signature (migrations.test_writer.OperationWriterTests)", "test_args_signature (migrations.test_writer.OperationWriterTests)", "test_empty_signature (migrations.test_writer.OperationWriterTests)", "test_expand_args_signature (migrations.test_writer.OperationWriterTests)", "test_kwargs_signature (migrations.test_writer.OperationWriterTests)", "test_multiline_args_signature (migrations.test_writer.OperationWriterTests)", "test_nested_args_signature (migrations.test_writer.OperationWriterTests)", "test_nested_operation_expand_args_signature (migrations.test_writer.OperationWriterTests)", "test_custom_operation (migrations.test_writer.WriterTests)", "test_deconstruct_class_arguments (migrations.test_writer.WriterTests)", "Test comments at top of file.", "test_migration_path (migrations.test_writer.WriterTests)", "django.db.models shouldn't be imported if unused.", "test_register_non_serializer (migrations.test_writer.WriterTests)", "test_register_serializer (migrations.test_writer.WriterTests)", "test_serialize_builtin_types (migrations.test_writer.WriterTests)", "test_serialize_builtins (migrations.test_writer.WriterTests)", "test_serialize_choices (migrations.test_writer.WriterTests)", "Ticket #22943: Test serialization of class-based validators, including", "test_serialize_collections (migrations.test_writer.WriterTests)", "Make sure compiled regex can be serialized.", "test_serialize_complex_func_index (migrations.test_writer.WriterTests)", "test_serialize_constants (migrations.test_writer.WriterTests)", "test_serialize_datetime (migrations.test_writer.WriterTests)", "Ticket #22679: makemigrations generates invalid code for (an empty", "test_serialize_enums (migrations.test_writer.WriterTests)", "test_serialize_fields (migrations.test_writer.WriterTests)", "test_serialize_frozensets (migrations.test_writer.WriterTests)", "test_serialize_functions (migrations.test_writer.WriterTests)", "test_serialize_functools_partial (migrations.test_writer.WriterTests)", "test_serialize_functools_partialmethod (migrations.test_writer.WriterTests)", "test_serialize_iterators (migrations.test_writer.WriterTests)", "test_serialize_lazy_objects (migrations.test_writer.WriterTests)", "A reference in a local scope can't be serialized.", "test_serialize_managers (migrations.test_writer.WriterTests)", "test_serialize_multiline_strings (migrations.test_writer.WriterTests)", "test_serialize_nested_class (migrations.test_writer.WriterTests)", "test_serialize_numbers (migrations.test_writer.WriterTests)", "test_serialize_path_like (migrations.test_writer.WriterTests)", "test_serialize_pathlib (migrations.test_writer.WriterTests)", "test_serialize_range (migrations.test_writer.WriterTests)", "test_serialize_set (migrations.test_writer.WriterTests)", "test_serialize_settings (migrations.test_writer.WriterTests)", "test_serialize_strings (migrations.test_writer.WriterTests)", "test_serialize_timedelta (migrations.test_writer.WriterTests)", "test_serialize_type_model (migrations.test_writer.WriterTests)", "test_serialize_type_none (migrations.test_writer.WriterTests)", "An unbound method used within a class body can be serialized.", "test_serialize_uuid (migrations.test_writer.WriterTests)", "Tests serializing a simple migration.", "#24155 - Tests ordering of imports."]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django__django-15252
null
null
django/db/migrations/executor.py
django/django
361bb8f786f112ee275be136795c0b1ecefff928
diff --git a/django/db/migrations/executor.py b/django/db/migrations/executor.py --- a/django/db/migrations/executor.py +++ b/django/db/migrations/executor.py @@ -96,8 +96,12 @@ def migrate(self, targets, plan=None, state=None, fake=False, fake_initial=False (un)applied and in a second step run all the database operations. """ # The django_migrations table must be present to record applied - # migrations. - self.recorder.ensure_schema() + # migrations, but don't create it if there are no migrations to apply. + if plan == []: + if not self.recorder.has_table(): + return self._create_project_state(with_applied_migrations=False) + else: + self.recorder.ensure_schema() if plan is None: plan = self.migration_plan(targets)
diff --git a/tests/backends/base/test_creation.py b/tests/backends/base/test_creation.py --- a/tests/backends/base/test_creation.py +++ b/tests/backends/base/test_creation.py @@ -57,12 +57,12 @@ def test_custom_test_name_with_test_prefix(self): @mock.patch.object(connection, 'ensure_connection') @mock.patch.object(connection, 'prepare_database') @mock.patch('django.db.migrations.recorder.MigrationRecorder.has_table', return_value=False) -@mock.patch('django.db.migrations.executor.MigrationExecutor.migrate') @mock.patch('django.core.management.commands.migrate.Command.sync_apps') class TestDbCreationTests(SimpleTestCase): available_apps = ['backends.base.app_unmigrated'] - def test_migrate_test_setting_false(self, mocked_sync_apps, mocked_migrate, *mocked_objects): + @mock.patch('django.db.migrations.executor.MigrationExecutor.migrate') + def test_migrate_test_setting_false(self, mocked_migrate, mocked_sync_apps, *mocked_objects): test_connection = get_connection_copy() test_connection.settings_dict['TEST']['MIGRATE'] = False creation = test_connection.creation_class(test_connection) @@ -86,7 +86,32 @@ def test_migrate_test_setting_false(self, mocked_sync_apps, mocked_migrate, *moc with mock.patch.object(creation, '_destroy_test_db'): creation.destroy_test_db(old_database_name, verbosity=0) - def test_migrate_test_setting_true(self, mocked_sync_apps, mocked_migrate, *mocked_objects): + @mock.patch('django.db.migrations.executor.MigrationRecorder.ensure_schema') + def test_migrate_test_setting_false_ensure_schema( + self, mocked_ensure_schema, mocked_sync_apps, *mocked_objects, + ): + test_connection = get_connection_copy() + test_connection.settings_dict['TEST']['MIGRATE'] = False + creation = test_connection.creation_class(test_connection) + if connection.vendor == 'oracle': + # Don't close connection on Oracle. + creation.connection.close = mock.Mock() + old_database_name = test_connection.settings_dict['NAME'] + try: + with mock.patch.object(creation, '_create_test_db'): + creation.create_test_db(verbosity=0, autoclobber=True, serialize=False) + # The django_migrations table is not created. + mocked_ensure_schema.assert_not_called() + # App is synced. + mocked_sync_apps.assert_called() + mocked_args, _ = mocked_sync_apps.call_args + self.assertEqual(mocked_args[1], {'app_unmigrated'}) + finally: + with mock.patch.object(creation, '_destroy_test_db'): + creation.destroy_test_db(old_database_name, verbosity=0) + + @mock.patch('django.db.migrations.executor.MigrationExecutor.migrate') + def test_migrate_test_setting_true(self, mocked_migrate, mocked_sync_apps, *mocked_objects): test_connection = get_connection_copy() test_connection.settings_dict['TEST']['MIGRATE'] = True creation = test_connection.creation_class(test_connection) @@ -109,6 +134,7 @@ def test_migrate_test_setting_true(self, mocked_sync_apps, mocked_migrate, *mock creation.destroy_test_db(old_database_name, verbosity=0) @mock.patch.dict(os.environ, {'RUNNING_DJANGOS_TEST_SUITE': ''}) + @mock.patch('django.db.migrations.executor.MigrationExecutor.migrate') @mock.patch.object(BaseDatabaseCreation, 'mark_expected_failures_and_skips') def test_mark_expected_failures_and_skips_call(self, mark_expected_failures_and_skips, *mocked_objects): """ diff --git a/tests/migrations/test_executor.py b/tests/migrations/test_executor.py --- a/tests/migrations/test_executor.py +++ b/tests/migrations/test_executor.py @@ -759,6 +759,17 @@ def apply(self, project_state, schema_editor, collect_sql=False): False, ) + @mock.patch.object(MigrationRecorder, 'has_table', return_value=False) + def test_migrate_skips_schema_creation(self, mocked_has_table): + """ + The django_migrations table is not created if there are no migrations + to record. + """ + executor = MigrationExecutor(connection) + # 0 queries, since the query for has_table is being mocked. + with self.assertNumQueries(0): + executor.migrate([], plan=[]) + class FakeLoader: def __init__(self, graph, applied):
MigrationRecorder does not obey db_router allow_migrate rules Description Hi, We have a multi-db setup. We have one connection that is for the django project, and several connections that talk to other dbs for information (ie models with managed = False). Django should only create tables in the first connection, never in any of the other connections. We have a simple router that does the following: class Router(object): def allow_migrate(self, db, model): if db == 'default': return True return False Current Behaviour We run our functional tests and the migrate command is called against each connection when the test databases are created (see django/test/runner.py, setup_databases, line 300-ish, which calls django/db/backends/creation.py, create_test_db, line 377-ish) When this migrate runs, it tries to apply our migrations, which tries to record that a migration has been applied (see django/db/migrations/executor.py, apply_migration, which has several calls to self.recorder.record_applied). The first thing that record_applied does is a call to self.ensure_schema() (see django/db/migrations/recorder.py, record_applied, lien 66-ish). ensure_schema checks to see if the Migration model is in the tables in the connection. If it does not find the table then it tries to create the table. I believe that this is incorrect behaviour when a db_router has been provided. If using the router above, my expectation would be that the table is not created on any connection other than the 'default' connection. Looking at the other methods on the MigrationRecorder, I would expect that there will be similar issues with applied_migrations and record_unapplied.
I don't think you've implemented your router correctly, but I'd need to check the router code to see if it's called multiple times (num_dbs*num_models) to be sure. This is how we implement our routers for allow_migrate: def allow_migrate(self, db, model): if db == 'other': return model._meta.app_label == 'legacy_app' # allow migration for new django models implemented in legacy db elif model._meta.app_label == 'legacy_app': # do not allow migration for legacy on any other db return False return None # this router not responsible So, I'm not sure if there is a bug or not (I'll let someone more familiar answer that), but this is what works for us. #22583 is somewhat related. It deals with the inability to skip RunSQL/RunPython operations on given database. @jarshwah: I don't think it is the router. Mainly because the router is not called at this point. Which is what I believe is the bug. @akaariai: I agree that there are similarities. Surely I should be able to manage which connections I actually run migrations against. That seems to be what the db_router is trying to do. I thought that something like the following would solve our problem: from django.db import router . . . def ensure_schema(self): """ Ensures the table exists and has the correct schema. """ # If the table's there, that's fine - we've never changed its schema # in the codebase. if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()): return # Make the table # Change below, similar to how allowed_to_migrate in django/db/migrations/operations/base.py works if router.allow_migrate(self.connection, self.Migration): with self.connection.schema_editor() as editor: editor.create_model(self.Migration) But this means that changes to applied_migrations, record_applied, and record_unapplied need to be made, so that it doesn't try to write to a none existent table. For us this is not an urgent issue, as we have appropriate permissions to those connections that are not our core connection. But I do have a concern for any time that we are using a true read-only connection, where we do not have the CREATE TABLE permission. Because this code, as it exists, will blow up in this situation. I tested that with a read-only connection in our db setup, and got an insufficient permissions error. Thanks, Dylan This is an issue, but bear in mind that migrate must be separately executed for each database alias, so this isn't going to happen unless you specifically run migrate on a database that you know isn't supposed to have migrations on it. I think the best fix would be to have migrations refuse to run entirely and just exit if the migration model is not allowed to be created on the target database. I see what you mean about the needing to run migarte for each database. I noticed this with the django test runner, where it is trying to run a migration against every connection alias that we have. So that might be an issue with the test runner as much as with the migrations stuff. Thanks, Dylan Just stumbled on this issue. With a properly written router, I expected the migrations of each app to be executed in the right database by just using : manage.py migrate Could this be the behavior ? Instead it's assuming I'm using the default database, OK, no, but ok :-)... and it doesn't follow the allow_migrate rule and creates in the default database the tables that are supposed to live exclusively in the another one (NOT OK !). So for now the workaround for me is to use a shell script where the app and the database are specified.: ./manage.py migrate inapppurchase --database=iap ./manage.py migrate myapp --database=default dperetti: Just like syncdb, migrate only runs on one database at a time, so you must execute it individually for each database, as you suggest. This is by design. froomzy: Yes, this is likely a test runner issue, that would be doing this kind of migrate-on-everything. I think the suggested fix of refusing to migrate databases where allow_migrate on the migration model returns False will still work, as long as it errors in a way we can catch in the test runner. Replying to andrewgodwin: dperetti: Just like syncdb, migrate only runs on one database at a time, so you must execute it individually for each database, as you suggest. This is by design. The question is : is it the best design ? When I run migrate, I don't want to know about how the router is configured. I just want to migrate the app. If the router dispatches the tables of an app to different databases, then I want migrate to operate on those. In other words, I think it would make sense to make migrate database agnostic. Another side issue : we cannot just manage.py migrate someapp if the someapp is a "django <1.7" app without migration : the old syncdb behavior is not applied when an application is specified. So if want the old apps to sync, I have to just run manage.py migrate, without argument... which will create unwanted tables when we have multiple databases. Hi guys, Just wondering if there is any chance this will make it into 1.8? Or soon there after? Thanks, Dylan It's not clear to me what fixing this issue involves exactly. Anyway, it doesn't appear anyone is working on it so there's no timetable for its resolution. I wanted to chime in here to broaden the scope of the bug, as I was affected by it recently in a different context. The bigger issue is not just that the framework tries to create the migrations table where it's not needed, but that it marks as applied migrations that in fact were not. That puts the database in an inconsistent state, at least as far as migrations are concerned. It's a harmless inconsistency for the specific settings file used at that specific moment in time, but it lays the seed for big problems down the line. For example, if you later decide to change your routing scheme, or (as happened in my case) if you have multiple projects with different settings using the same app on the same database. In terms of a solution, what seems straightforward to my untrained eye is for the migration framework to simply not record migrations as applied that it didn't apply (and as a corollary, it shouldn't try to create the migration table on a database if it doesn't need to record any migrations there). The fix suggested above ("to have migrations refuse to run entirely and just exit if the migration model is not allowed to be created on the target database") doesn't address the broader issue. Let me amend my last comment: I think that having migrate blow up in this situation would in fact solve the problem with having an inconsistent migrations table, which is the most important thing. My question is, since allow_migrate() operates at the model level and the migrate command operates at the app level, wouldn't this make it impossible to migrate some models of an app but not others? I can confirm marfire's findings. 1/ For example even with this router applied: class testerouter(object): def allow_migrate(self, db, app_label, model_name=None, **hints): return False And then executing: migrate --database=replica All apps and models migrations get applied to this replica database, while according to the router nothing should happen at all. 2/ From the documentation it is not clear whether it is possible to isolate certain models from certain databases, or whether isolation can only be done on the app-level. From the description in the documentation, it seems possible to use the model_name argument for this, but by the way django stores its migrations, I don't see how that could work. Just to further confirm: I've been wrestling with this problem for a couple days. I have multiple databases and multiple apps. When I'm running tests, the router allow_migrate works properly to control which migrations can be applied to which database/app. The actual migration portion works fine, but when it comes time to actually write the migration history, it seems to only have a concept of the default database. When it runs ensure_schema, it's expecting that tables should exist on the default DB when they really only exist for certain other apps/databases. This leads to a ProgrammingError where it can't find tables that it shouldn't be checking for in the first place. Can you please have a look at ​http://stackoverflow.com/questions/40893868/using-redshift-as-an-additional-django-database?noredirect=1#comment69004673_40893868, which provides a decent use case for this bug. Since 3.1 you can set 'TEST': {'MIGRATE': False} to avoid running migrations on a given db connection, so that solves the test runner issue. Still, even if you do that, apps are still synced (see fix to #32012), Django ends up calling migrate to do the syncing, and this will cause queries in MigrationRecorder.ensure_schema() that might create tables (or fail with permission errors, see #27141). I plan to open a PR to do roughly this from comment:13: it shouldn't try to create the migration table on a database if it doesn't need to record any migrations there
2021-12-28T15:51:06Z
4.1
["test_migrate_test_setting_false_ensure_schema (backends.base.test_creation.TestDbCreationTests)", "The django_migrations table is not created if there are no migrations"]
["test_mark_expected_failures_and_skips (backends.base.test_creation.TestMarkTests)", "test_custom_test_name (backends.base.test_creation.TestDbSignatureTests)", "test_custom_test_name_with_test_prefix (backends.base.test_creation.TestDbSignatureTests)", "test_default_name (backends.base.test_creation.TestDbSignatureTests)", "If the current state satisfies the given target, do nothing.", "Minimize unnecessary rollbacks in connected apps.", "Minimize rollbacks when target has multiple in-app children.", "mark_expected_failures_and_skips() isn't called unless", "test_migrate_test_setting_false (backends.base.test_creation.TestDbCreationTests)", "test_migrate_test_setting_true (backends.base.test_creation.TestDbCreationTests)", "test_circular_reference (backends.base.test_creation.TestDeserializeDbFromString)", "test_circular_reference_with_natural_key (backends.base.test_creation.TestDeserializeDbFromString)", "test_self_reference (backends.base.test_creation.TestDeserializeDbFromString)", "test_serialize_db_to_string_base_manager (backends.base.test_creation.TestDeserializeDbFromString)", "test_alter_id_type_with_fk (migrations.test_executor.ExecutorTests)", "Applying all replaced migrations marks replacement as applied (#24628).", "An atomic operation is properly rolled back inside a non-atomic", "Regression test for #22325 - references to a custom user model defined in the", "executor.detect_soft_applied() detects ManyToManyField tables from an", "Re-planning a full migration of a fully-migrated set doesn't", "test_migrate_backward_to_squashed_migration (migrations.test_executor.ExecutorTests)", "A new squash migration will be marked as applied even if all its", "test_migrate_marks_replacement_unapplied (migrations.test_executor.ExecutorTests)", "Migrations are applied and recorded atomically.", "Migrations are not recorded if deferred SQL application fails.", "Although the MigrationExecutor interfaces allows for mixed migration", "Applying a non-atomic migration works as expected.", "#24129 - Tests callback process", "Tests running a simple set of migrations.", "Tests running a squashed migration from zero (should ignore what it replaces)", "Tests detection of initial migrations already having been applied.", "#26647 - Unrelated applied migrations should be part of the final", "#24123 - All models of apps being unapplied which are", "#24123 - All models of apps already applied which are"]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django__django-11797
description of a file might be useful
2
django/db/models/lookups.py
django/django
3346b78a8a872286a245d1e77ef4718fc5e6be1a
diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -262,9 +262,9 @@ def process_rhs(self, compiler, connection): from django.db.models.sql.query import Query if isinstance(self.rhs, Query): if self.rhs.has_limit_one(): - # The subquery must select only the pk. - self.rhs.clear_select_clause() - self.rhs.add_fields(['pk']) + 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 '
diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -5,6 +5,7 @@ from django.core.exceptions import FieldError from django.db import connection +from django.db.models import Max from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Substr from django.test import TestCase, skipUnlessDBFeature @@ -956,3 +957,15 @@ def test_nested_outerref_lhs(self): ), ) 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)
Filtering on query result overrides GROUP BY of internal query Description from django.contrib.auth import models a = models.User.objects.filter(email__isnull=True).values('email').annotate(m=Max('id')).values('m') print(a.query) # good # SELECT MAX("auth_user"."id") AS "m" FROM "auth_user" WHERE "auth_user"."email" IS NULL GROUP BY "auth_user"."email" print(a[:1].query) # good # SELECT MAX("auth_user"."id") AS "m" FROM "auth_user" WHERE "auth_user"."email" IS NULL GROUP BY "auth_user"."email" LIMIT 1 b = models.User.objects.filter(id=a[:1]) print(b.query) # GROUP BY U0."id" should be GROUP BY U0."email" # SELECT ... FROM "auth_user" WHERE "auth_user"."id" = (SELECT U0."id" FROM "auth_user" U0 WHERE U0."email" IS NULL GROUP BY U0."id" LIMIT 1)
Workaround: from django.contrib.auth import models a = models.User.objects.filter(email__isnull=True).values('email').aggregate(Max('id'))['id_max'] b = models.User.objects.filter(id=a) Thanks for tackling that one James! If I can provide you some guidance I'd suggest you have a look at lookups.Exact.process_rhs ​https://github.com/django/django/blob/ea25bdc2b94466bb1563000bf81628dea4d80612/django/db/models/lookups.py#L265-L267 We probably don't want to perform the clear_select_clause and add_fields(['pk']) when the query is already selecting fields. That's exactly what In.process_rhs ​does already by only performing these operations if not getattr(self.rhs, 'has_select_fields', True). Thanks so much for the help Simon! This is a great jumping-off point. There's something that I'm unclear about, which perhaps you can shed some light on. While I was able to replicate the bug with 2.2, when I try to create a test on Master to validate the bug, the group-by behavior seems to have changed. Here's the test that I created: def test_exact_selected_field_rhs_subquery(self): author_1 = Author.objects.create(name='one') author_2 = Author.objects.create(name='two') max_ids = Author.objects.filter(alias__isnull=True).values('alias').annotate(m=Max('id')).values('m') authors = Author.objects.filter(id=max_ids[:1]) self.assertFalse(str(max_ids.query)) # This was just to force the test-runner to output the query. self.assertEqual(authors[0], author_2) And here's the resulting query: SELECT MAX("lookup_author"."id") AS "m" FROM "lookup_author" WHERE "lookup_author"."alias" IS NULL GROUP BY "lookup_author"."alias", "lookup_author"."name" It no longer appears to be grouping by the 'alias' field listed in the initial .values() preceeding the .annotate(). I looked at the docs and release notes to see if there was a behavior change, but didn't see anything listed. Do you know if I'm just misunderstanding what's happening here? Or does this seem like a possible regression? It's possible that a regression was introduced in between. Could you try bisecting the commit that changed the behavior ​https://docs.djangoproject.com/en/dev/internals/contributing/triaging-tickets/#bisecting-a-regression Mmm actually disregard that. The second value in the GROUP BY is due to the ordering value in the Author class's Meta class. class Author(models.Model): name = models.CharField(max_length=100) alias = models.CharField(max_length=50, null=True, blank=True) class Meta: ordering = ('name',) Regarding the bug in question in this ticket, what should the desired behavior be if the inner query is returning multiple fields? With the fix, which allows the inner query to define a field to return/group by, if there are multiple fields used then it will throw a sqlite3.OperationalError: row value misused. Is this the desired behavior or should it avoid this problem by defaulting back to pk if more than one field is selected? I think that we should only default to pk if no fields are selected. The ORM has preliminary support for multi-column lookups and other interface dealing with subqueries doesn't prevent passing queries with multiple fields so I'd stick to the current __in lookup behavior.
2019-09-20T02:23:19Z
3.1
["test_exact_query_rhs_with_selected_columns (lookup.tests.LookupTests)"]
["test_chain_date_time_lookups (lookup.tests.LookupTests)", "test_count (lookup.tests.LookupTests)", "test_custom_field_none_rhs (lookup.tests.LookupTests)", "Lookup.can_use_none_as_rhs=True allows None as a lookup value.", "test_error_messages (lookup.tests.LookupTests)", "test_escaping (lookup.tests.LookupTests)", "test_exact_exists (lookup.tests.LookupTests)", "Transforms are used for __exact=None.", "test_exact_sliced_queryset_limit_one (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one_offset (lookup.tests.LookupTests)", "test_exact_sliced_queryset_not_limited_to_one (lookup.tests.LookupTests)", "test_exclude (lookup.tests.LookupTests)", "test_exists (lookup.tests.LookupTests)", "test_get_next_previous_by (lookup.tests.LookupTests)", "test_in (lookup.tests.LookupTests)", "test_in_bulk (lookup.tests.LookupTests)", "test_in_bulk_lots_of_ids (lookup.tests.LookupTests)", "test_in_bulk_non_unique_field (lookup.tests.LookupTests)", "test_in_bulk_with_field (lookup.tests.LookupTests)", "test_in_different_database (lookup.tests.LookupTests)", "test_in_keeps_value_ordering (lookup.tests.LookupTests)", "test_iterator (lookup.tests.LookupTests)", "test_lookup_collision (lookup.tests.LookupTests)", "test_lookup_date_as_str (lookup.tests.LookupTests)", "test_lookup_int_as_str (lookup.tests.LookupTests)", "test_nested_outerref_lhs (lookup.tests.LookupTests)", "test_none (lookup.tests.LookupTests)", "test_nonfield_lookups (lookup.tests.LookupTests)", "test_pattern_lookups_with_substr (lookup.tests.LookupTests)", "test_regex (lookup.tests.LookupTests)", "test_regex_backreferencing (lookup.tests.LookupTests)", "test_regex_non_ascii (lookup.tests.LookupTests)", "test_regex_non_string (lookup.tests.LookupTests)", "test_regex_null (lookup.tests.LookupTests)", "test_relation_nested_lookup_error (lookup.tests.LookupTests)", "test_unsupported_lookups (lookup.tests.LookupTests)", "test_values (lookup.tests.LookupTests)", "test_values_list (lookup.tests.LookupTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django__django-16046
can understand exact file
0
django/utils/numberformat.py
django/django
ec13e801b820614ff374cb0046092caab8d67249
diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py --- a/django/utils/numberformat.py +++ b/django/utils/numberformat.py @@ -25,6 +25,8 @@ def format( module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example ",") """ + if number is None or number == "": + return mark_safe(number) use_grouping = ( use_l10n or (use_l10n is None and settings.USE_L10N) ) and settings.USE_THOUSAND_SEPARATOR
diff --git a/tests/utils_tests/test_numberformat.py b/tests/utils_tests/test_numberformat.py --- a/tests/utils_tests/test_numberformat.py +++ b/tests/utils_tests/test_numberformat.py @@ -172,3 +172,7 @@ def __format__(self, specifier, **kwargs): price = EuroDecimal("1.23") self.assertEqual(nformat(price, ","), "€ 1,23") + + def test_empty(self): + self.assertEqual(nformat("", "."), "") + self.assertEqual(nformat(None, "."), "None")
Fix numberformat.py "string index out of range" when null Description When: if str_number[0] == "-" encounters a number field that's null when formatting for the admin list_display this causes an IndexError: string index out of range I can attach the proposed fix here, or open a pull request on GitHub if you like?
proposed fix patch Please provide a pull request, including a test.
2022-09-10T13:27:38Z
4.2
["test_empty (utils_tests.test_numberformat.TestNumberFormat)"]
["test_decimal_numbers (utils_tests.test_numberformat.TestNumberFormat)", "test_decimal_subclass (utils_tests.test_numberformat.TestNumberFormat)", "test_float_numbers (utils_tests.test_numberformat.TestNumberFormat)", "test_format_number (utils_tests.test_numberformat.TestNumberFormat)", "test_format_string (utils_tests.test_numberformat.TestNumberFormat)", "test_large_number (utils_tests.test_numberformat.TestNumberFormat)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django__django-11583
null
2
django/utils/autoreload.py
django/django
60dc957a825232fdda9138e2f8878b2ca407a7c9
diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py --- a/django/utils/autoreload.py +++ b/django/utils/autoreload.py @@ -143,6 +143,10 @@ def iter_modules_and_files(modules, extra_files): # The module could have been removed, don't fail loudly if this # is the case. continue + except ValueError as e: + # Network filesystems may return null bytes in file paths. + logger.debug('"%s" raised when resolving path: "%s"' % (str(e), path)) + continue results.add(resolved_path) return frozenset(results)
diff --git a/tests/utils_tests/test_autoreload.py b/tests/utils_tests/test_autoreload.py --- a/tests/utils_tests/test_autoreload.py +++ b/tests/utils_tests/test_autoreload.py @@ -140,6 +140,17 @@ def test_main_module_without_file_is_not_resolved(self): fake_main = types.ModuleType('__main__') self.assertEqual(autoreload.iter_modules_and_files((fake_main,), frozenset()), frozenset()) + def test_path_with_embedded_null_bytes(self): + for path in ( + 'embedded_null_byte\x00.py', + 'di\x00rectory/embedded_null_byte.py', + ): + with self.subTest(path=path): + self.assertEqual( + autoreload.iter_modules_and_files((), frozenset([path])), + frozenset(), + ) + class TestCommonRoots(SimpleTestCase): def test_common_roots(self):
Auto-reloading with StatReloader very intermittently throws "ValueError: embedded null byte". Description Raising this mainly so that it's tracked, as I have no idea how to reproduce it, nor why it's happening. It ultimately looks like a problem with Pathlib, which wasn't used prior to 2.2. Stacktrace: Traceback (most recent call last): File "manage.py" ... execute_from_command_line(sys.argv) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 577, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 562, in start_django reloader.run(django_main_thread) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 280, in run self.run_loop() File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 286, in run_loop next(ticker) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 326, in tick for filepath, mtime in self.snapshot_files(): File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 342, in snapshot_files for file in self.watched_files(): File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 241, in watched_files yield from iter_all_python_module_files() File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/Userz/kez/path/to/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 132, in iter_modules_and_files results.add(path.resolve().absolute()) File "/Users/kez/.pyenv/versions/3.6.2/lib/python3.6/pathlib.py", line 1120, in resolve s = self._flavour.resolve(self, strict=strict) File "/Users/kez/.pyenv/versions/3.6.2/lib/python3.6/pathlib.py", line 346, in resolve return _resolve(base, str(path)) or sep File "/Users/kez/.pyenv/versions/3.6.2/lib/python3.6/pathlib.py", line 330, in _resolve target = accessor.readlink(newpath) File "/Users/kez/.pyenv/versions/3.6.2/lib/python3.6/pathlib.py", line 441, in readlink return os.readlink(path) ValueError: embedded null byte I did print(path) before os.readlink(path) in pathlib and ended up with: /Users/kez /Users/kez/.pyenv /Users/kez/.pyenv/versions /Users/kez/.pyenv/versions/3.6.2 /Users/kez/.pyenv/versions/3.6.2/lib /Users/kez/.pyenv/versions/3.6.2/lib/python3.6 /Users/kez/.pyenv/versions/3.6.2/lib/python3.6/asyncio /Users/kez/.pyenv/versions/3.6.2/lib/python3.6/asyncio/selector_events.py /Users It always seems to be /Users which is last It may have already printed /Users as part of another .resolve() multiple times (that is, the order is not deterministic, and it may have traversed beyond /Users successfully many times during startup. I don't know where to begin looking for the rogue null byte, nor why it only exists sometimes. Best guess I have is that there's a mountpoint in /Users to a samba share which may not have been connected to yet? I dunno. I have no idea if it's fixable without removing the use of pathlib (which tbh I think should happen anyway, because it's slow) and reverting to using os.path.join and friends. I have no idea if it's fixed in a later Python version, but with no easy way to reproduce ... dunno how I'd check. I have no idea if it's something specific to my system (pyenv, OSX 10.11, etc)
Thanks for the report, however as you've admitted there is too many unknowns to accept this ticket. I don't believe that it is related with pathlib, maybe samba connection is unstable it's hard to tell. I don't believe that it is related with pathlib Well ... it definitely is, you can see that from the stacktrace. The difference between 2.2 and 2.1 (and every version prior) for the purposes of this report is that AFAIK 2.2 is using pathlib.resolve() which deals with symlinks where under <2.2 I don't think the equivalent (os.path.realpath rather than os.path.abspath) was used. But yes, there's no path forward to fix the ticket as it stands, short of not using pathlib (or at least .resolve()). Hey Keryn, Have you tried removing resolve() yourself, and did it fix the issue? I chose to use resolve() to try and work around a corner case with symlinks, and to generally just normalize the paths to prevent duplication. Also, regarding your comment above, you would need to use print(repr(path)), as I think the print machinery stops at the first null byte found (hence just /Users, which should never be monitored by itself). If you can provide me some more information I'm more than willing to look into this, or consider removing the resolve() call. Replying to Tom Forbes: Hey Keryn, Have you tried removing resolve() yourself, and did it fix the issue? I chose to use resolve() to try and work around a corner case with symlinks, and to generally just normalize the paths to prevent duplication. Also, regarding your comment above, you would need to use print(repr(path)), as I think the print machinery stops at the first null byte found (hence just /Users, which should never be monitored by itself). If you can provide me some more information I'm more than willing to look into this, or consider removing the resolve() call. Hi Tom, I am also getting this error, see here for the stackoverflow question which I have attempted to answer: ​https://stackoverflow.com/questions/56406965/django-valueerror-embedded-null-byte/56685648#56685648 What is really odd is that it doesn't error every time and looks to error on a random file each time. I believe the issue is caused by having a venv within the top level directory but might be wrong. Bug is on all versions of django >= 2.2.0 Felix, I'm going to re-open this ticket if that's OK. While this is clearly something "funky" going on at a lower level than we handle, it used to work (at least, the error was swallowed). I think this is a fairly simple fix.
2019-07-21T20:56:14Z
3.0
["test_path_with_embedded_null_bytes (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_paths_are_pathlib_instances (utils_tests.test_autoreload.TestIterModulesAndFiles)"]
["test_no_exception (utils_tests.test_autoreload.TestRaiseLastException)", "test_raises_custom_exception (utils_tests.test_autoreload.TestRaiseLastException)", "test_raises_exception (utils_tests.test_autoreload.TestRaiseLastException)", "test_raises_exception_with_context (utils_tests.test_autoreload.TestRaiseLastException)", "test_watchman_available (utils_tests.test_autoreload.GetReloaderTests)", "test_watchman_unavailable (utils_tests.test_autoreload.GetReloaderTests)", "test_common_roots (utils_tests.test_autoreload.TestCommonRoots)", "test_calls_start_django (utils_tests.test_autoreload.RunWithReloaderTests)", "test_calls_sys_exit (utils_tests.test_autoreload.RunWithReloaderTests)", "test_swallows_keyboard_interrupt (utils_tests.test_autoreload.RunWithReloaderTests)", "test_mutates_error_files (utils_tests.test_autoreload.TestCheckErrors)", "test_sys_paths_absolute (utils_tests.test_autoreload.TestSysPathDirectories)", "test_sys_paths_directories (utils_tests.test_autoreload.TestSysPathDirectories)", "test_sys_paths_non_existing (utils_tests.test_autoreload.TestSysPathDirectories)", "test_sys_paths_with_directories (utils_tests.test_autoreload.TestSysPathDirectories)", "test_manage_py (utils_tests.test_autoreload.RestartWithReloaderTests)", "test_python_m_django (utils_tests.test_autoreload.RestartWithReloaderTests)", "test_run_loop_catches_stopiteration (utils_tests.test_autoreload.BaseReloaderTests)", "test_run_loop_stop_and_return (utils_tests.test_autoreload.BaseReloaderTests)", "test_wait_for_apps_ready_checks_for_exception (utils_tests.test_autoreload.BaseReloaderTests)", "test_wait_for_apps_ready_without_exception (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_files_with_recursive_glob (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_with_glob (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_with_single_file (utils_tests.test_autoreload.BaseReloaderTests)", "test_watch_without_absolute (utils_tests.test_autoreload.BaseReloaderTests)", "test_file (utils_tests.test_autoreload.StatReloaderTests)", "test_glob (utils_tests.test_autoreload.StatReloaderTests)", "test_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)", "test_multiple_globs (utils_tests.test_autoreload.StatReloaderTests)", "test_multiple_recursive_globs (utils_tests.test_autoreload.StatReloaderTests)", "test_nested_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)", "test_overlapping_glob_recursive (utils_tests.test_autoreload.StatReloaderTests)", "test_overlapping_globs (utils_tests.test_autoreload.StatReloaderTests)", "test_snapshot_files_ignores_missing_files (utils_tests.test_autoreload.StatReloaderTests)", "test_snapshot_files_updates (utils_tests.test_autoreload.StatReloaderTests)", "test_snapshot_files_with_duplicates (utils_tests.test_autoreload.StatReloaderTests)", "test_tick_does_not_trigger_twice (utils_tests.test_autoreload.StatReloaderTests)", "test_check_errors_called (utils_tests.test_autoreload.StartDjangoTests)", "test_echo_on_called (utils_tests.test_autoreload.StartDjangoTests)", "test_starts_thread_with_args (utils_tests.test_autoreload.StartDjangoTests)", "test_watchman_becomes_unavailable (utils_tests.test_autoreload.StartDjangoTests)", ".pyc and .pyo files are included in the files list.", "test_check_errors (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_check_errors_catches_all_exceptions (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_file_added (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_main_module_is_resolved (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_main_module_without_file_is_not_resolved (utils_tests.test_autoreload.TestIterModulesAndFiles)", "test_module_without_spec (utils_tests.test_autoreload.TestIterModulesAndFiles)", "iter_all_python_module_file() ignores weakref modules.", "test_zip_reload (utils_tests.test_autoreload.TestIterModulesAndFiles)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django__django-15738
need to identify issue is with migrate file
1
django/db/migrations/autodetector.py
django/django
6f73eb9d90cfec684529aab48d517e3d6449ba8c
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -1022,8 +1022,9 @@ def generate_added_fields(self): def _generate_added_field(self, app_label, model_name, field_name): field = self.to_state.models[app_label, model_name].get_field(field_name) - # Fields that are foreignkeys/m2ms depend on stuff - dependencies = [] + # 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(
diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py --- a/tests/migrations/test_autodetector.py +++ b/tests/migrations/test_autodetector.py @@ -868,6 +868,18 @@ class AutodetectorTests(TestCase): "unique_together": {("title", "newfield2")}, }, ) + book_unique_together = ModelState( + "otherapp", + "Book", + [ + ("id", models.AutoField(primary_key=True)), + ("author", models.ForeignKey("testapp.Author", models.CASCADE)), + ("title", models.CharField(max_length=200)), + ], + { + "unique_together": {("author", "title")}, + }, + ) attribution = ModelState( "otherapp", "Attribution", @@ -3798,16 +3810,16 @@ def test_many_to_many_changed_to_concrete_field(self): # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( - changes, "testapp", 0, ["RemoveField", "AddField", "DeleteModel"] + changes, "testapp", 0, ["RemoveField", "DeleteModel", "AddField"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="publishers", model_name="author" ) + self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes( - changes, "testapp", 0, 1, name="publishers", model_name="author" + changes, "testapp", 0, 2, name="publishers", model_name="author" ) - self.assertOperationAttributes(changes, "testapp", 0, 2, name="Publisher") - self.assertOperationFieldAttributes(changes, "testapp", 0, 1, max_length=100) + self.assertOperationFieldAttributes(changes, "testapp", 0, 2, max_length=100) def test_non_circular_foreignkey_dependency_removal(self): """ @@ -4346,6 +4358,36 @@ def test_fk_dependency_other_app(self): changes, "testapp", 0, [("otherapp", "__first__")] ) + def test_alter_unique_together_fk_to_m2m(self): + changes = self.get_changes( + [self.author_name, self.book_unique_together], + [ + self.author_name, + ModelState( + "otherapp", + "Book", + [ + ("id", models.AutoField(primary_key=True)), + ("author", models.ManyToManyField("testapp.Author")), + ("title", models.CharField(max_length=200)), + ], + ), + ], + ) + self.assertNumberMigrations(changes, "otherapp", 1) + self.assertOperationTypes( + changes, "otherapp", 0, ["AlterUniqueTogether", "RemoveField", "AddField"] + ) + self.assertOperationAttributes( + changes, "otherapp", 0, 0, name="book", unique_together=set() + ) + self.assertOperationAttributes( + changes, "otherapp", 0, 1, model_name="book", name="author" + ) + self.assertOperationAttributes( + changes, "otherapp", 0, 2, model_name="book", name="author" + ) + def test_alter_field_to_fk_dependency_other_app(self): changes = self.get_changes( [self.author_empty, self.book_with_no_author_fk],
Models migration with change field foreign to many and deleting unique together. Description (last modified by Simon Charette) I have models like class Authors(models.Model): project_data_set = models.ForeignKey( ProjectDataSet, on_delete=models.PROTECT ) state = models.IntegerField() start_date = models.DateField() class Meta: unique_together = (('project_data_set', 'state', 'start_date'),) and class DataSet(models.Model): name = models.TextField(max_length=50) class Project(models.Model): data_sets = models.ManyToManyField( DataSet, through='ProjectDataSet', ) name = models.TextField(max_length=50) class ProjectDataSet(models.Model): """ Cross table of data set and project """ data_set = models.ForeignKey(DataSet, on_delete=models.PROTECT) project = models.ForeignKey(Project, on_delete=models.PROTECT) class Meta: unique_together = (('data_set', 'project'),) when i want to change field project_data_set in Authors model from foreign key field to many to many field I must delete a unique_together, cause it can't be on many to many field. Then my model should be like: class Authors(models.Model): project_data_set = models.ManyToManyField( ProjectDataSet, ) state = models.IntegerField() start_date = models.DateField() But when I want to do a migrations. python3 manage.py makemigrations python3 manage.py migrate I have error: ValueError: Found wrong number (0) of constraints for app_authors(project_data_set, state, start_date) The database is on production, so I can't delete previous initial migrations, and this error isn't depending on database, cause I delete it and error is still the same. My solve is to first delete unique_together, then do a makemigrations and then migrate. After that change the field from foreign key to many to many field, then do a makemigrations and then migrate. But in this way I have 2 migrations instead of one. I added attachment with this project, download it and then do makemigrations and then migrate to see this error.
Download this file and then do makemigrations and migrate to see this error. Thanks for the report. Tentatively accepting, however I'm not sure if we can sort these operations properly, we should probably alter unique_together first migrations.AlterUniqueTogether( name='authors', unique_together=set(), ), migrations.RemoveField( model_name='authors', name='project_data_set', ), migrations.AddField( model_name='authors', name='project_data_set', field=models.ManyToManyField(to='dict.ProjectDataSet'), ), You should take into account that you'll lose all data because ForeignKey cannot be altered to ManyToManyField. I agree that you'll loose data but Alter(Index|Unique)Together should always be sorted before RemoveField ​https://github.com/django/django/blob/b502061027b90499f2e20210f944292cecd74d24/django/db/migrations/autodetector.py#L910 ​https://github.com/django/django/blob/b502061027b90499f2e20210f944292cecd74d24/django/db/migrations/autodetector.py#L424-L430 So something's broken here in a few different ways and I suspect it's due to the fact the same field name project_data_set is reused for the many-to-many field. If you start from class Authors(models.Model): project_data_set = models.ForeignKey( ProjectDataSet, on_delete=models.PROTECT ) state = models.IntegerField() start_date = models.DateField() class Meta: unique_together = (('project_data_set', 'state', 'start_date'),) And generate makemigrations for class Authors(models.Model): project_data_set = models.ManyToManyField(ProjectDataSet) state = models.IntegerField() start_date = models.DateField() You'll get two migrations with the following operations # 0002 operations = [ migrations.AddField( model_name='authors', name='project_data_set', field=models.ManyToManyField(to='ticket_31788.ProjectDataSet'), ), migrations.AlterUniqueTogether( name='authors', unique_together=set(), ), migrations.RemoveField( model_name='authors', name='project_data_set', ), ] # 0003 operations = [ migrations.AddField( model_name='authors', name='project_data_set', field=models.ManyToManyField(to='ticket_31788.ProjectDataSet'), ), ] If you change the name of the field to something else like project_data_sets every work as expected operations = [ migrations.AddField( model_name='authors', name='project_data_sets', field=models.ManyToManyField(to='ticket_31788.ProjectDataSet'), ), migrations.AlterUniqueTogether( name='authors', unique_together=set(), ), migrations.RemoveField( model_name='authors', name='project_data_set', ), ] It seems like there's some bad interactions between generate_removed_fields and generate_added_fields when a field with the same name is added.
2022-05-27T13:20:14Z
4.2
["test_alter_unique_together_fk_to_m2m (migrations.test_autodetector.AutodetectorTests)", "#23938 - Changing a ManyToManyField into a concrete field"]
["test_auto (migrations.test_autodetector.MigrationSuggestNameTests)", "test_many_operations_suffix (migrations.test_autodetector.MigrationSuggestNameTests)", "test_no_operations (migrations.test_autodetector.MigrationSuggestNameTests)", "test_no_operations_initial (migrations.test_autodetector.MigrationSuggestNameTests)", "test_none_name (migrations.test_autodetector.MigrationSuggestNameTests)", "test_none_name_with_initial_true (migrations.test_autodetector.MigrationSuggestNameTests)", "test_operation_with_no_suggested_name (migrations.test_autodetector.MigrationSuggestNameTests)", "test_single_operation (migrations.test_autodetector.MigrationSuggestNameTests)", "test_single_operation_long_name (migrations.test_autodetector.MigrationSuggestNameTests)", "test_two_create_models (migrations.test_autodetector.MigrationSuggestNameTests)", "test_two_create_models_with_initial_true (migrations.test_autodetector.MigrationSuggestNameTests)", "test_two_operations (migrations.test_autodetector.MigrationSuggestNameTests)", "Setting order_with_respect_to when adding the FK too does", "#23405 - Adding a NOT NULL and blank `CharField` or `TextField`", "Test change detection of new constraints.", "test_add_custom_fk_with_hardcoded_to (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_add_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_add_not_asking_for_null_addition (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_not_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of new fields.", "Added fields will be created before using them in index/unique_together.", "#22030 - Adding a field with a default should work.", "Tests index/unique_together detection.", "Test change detection of new indexes.", "#22435 - Adding a ManyToManyField should not prompt for a default.", "Setting order_with_respect_to when adding the whole model", "test_add_model_order_with_respect_to_index_constraint (migrations.test_autodetector.AutodetectorTests)", "test_add_model_order_with_respect_to_index_foo_together (migrations.test_autodetector.AutodetectorTests)", "Removing a base field takes place before adding a new inherited model", "#23405 - Adding a NOT NULL and non-blank `CharField` or `TextField`", "Tests detection for adding db_table in model's options.", "Tests detection for changing db_table in model's options'.", "Alter_db_table doesn't generate a migration if no changes have been made.", "Tests detection for removing db_table in model's options.", "Tests when model and db_table changes, autodetector must create two", "Fields are altered after deleting some index/unique_together.", "test_alter_field_to_fk_dependency_other_app (migrations.test_autodetector.AutodetectorTests)", "#23609 - Tests autodetection of nullable to non-nullable alterations.", "ForeignKeys are altered _before_ the model they used to", "test_alter_many_to_many (migrations.test_autodetector.AutodetectorTests)", "Changing the model managers adds a new operation.", "Changing a model's options should make a change.", "Changing a proxy model's options should also make a change.", "test_alter_regex_string_to_compiled_regex (migrations.test_autodetector.AutodetectorTests)", "Tests auto-naming of migrations for graph matching.", "test_arrange_for_graph_with_multiple_initial (migrations.test_autodetector.AutodetectorTests)", "Bases of other models come first.", "test_bases_first_mixed_case_app_label (migrations.test_autodetector.AutodetectorTests)", "#23315 - The dependency resolver knows to put all CreateModel", "#23322 - The dependency resolver knows to explicitly resolve", "Having a circular ForeignKey dependency automatically", "#23938 - Changing a concrete field into a ManyToManyField", "test_create_model_and_unique_together (migrations.test_autodetector.AutodetectorTests)", "Test creation of new model with constraints already defined.", "Test creation of new model with indexes already defined.", "Adding a m2m with a through model and the models that use it should be", "Two instances which deconstruct to the same value aren't considered a", "Tests custom naming of migrations for graph matching.", "Field instances are handled correctly by nested deconstruction.", "#22951 -- Uninstantiated classes with deconstruct are correctly returned", "Nested deconstruction descends into dict values.", "Nested deconstruction descends into lists.", "Nested deconstruction descends into tuples.", "test_default_related_name_option (migrations.test_autodetector.AutodetectorTests)", "test_different_regex_does_alter (migrations.test_autodetector.AutodetectorTests)", "#23452 - Empty unique/index_together shouldn't generate a migration.", "A dependency to an app with no migrations uses __first__.", "Having a ForeignKey automatically adds a dependency.", "#23100 - ForeignKeys correctly depend on other apps' models.", "index/unique_together doesn't generate a migration if no", "index/unique_together also triggers on ordering changes.", "Tests unique_together and field removal detection & ordering", "Removing an FK and the model it targets in the same change must remove", "test_identical_regex_doesnt_alter (migrations.test_autodetector.AutodetectorTests)", "Tests when model changes but db_table stays as-is, autodetector must not", "A dependency to an app with existing migrations uses the", "A model with a m2m field that specifies a \"through\" model cannot be", "test_managed_to_unmanaged (migrations.test_autodetector.AutodetectorTests)", "Removing a ManyToManyField and the \"through\" model in the same change", "Removing a model that contains a ManyToManyField and the \"through\" model", "test_mti_inheritance_model_removal (migrations.test_autodetector.AutodetectorTests)", "Inheriting models doesn't move *_ptr fields into AddField operations.", "Nested deconstruction is applied recursively to the args/kwargs of", "Tests autodetection of new models.", "If two models with a ForeignKey from one to the other are removed at the", "Tests deletion of old models.", "Test change detection of reordering of fields in indexes.", "test_parse_number (migrations.test_autodetector.AutodetectorTests)", "test_partly_alter_foo_together (migrations.test_autodetector.AutodetectorTests)", "A relation used as the primary key is kept as part of CreateModel.", "The autodetector correctly deals with proxy models.", "Bases of proxies come first.", "#23415 - The autodetector must correctly deal with custom FK on proxy", "FK dependencies still work on proxy models.", "test_proxy_non_model_parent (migrations.test_autodetector.AutodetectorTests)", "test_proxy_to_mti_with_fk_to_proxy (migrations.test_autodetector.AutodetectorTests)", "test_proxy_to_mti_with_fk_to_proxy_proxy (migrations.test_autodetector.AutodetectorTests)", "Removing order_with_respect_to when removing the FK too does", "Test change detection of removed constraints.", "Tests autodetection of removed fields.", "Removed fields will be removed after updating index/unique_together.", "Test change detection of removed indexes.", "Tests autodetection of renamed fields.", "Fields are renamed before updating index/unique_together.", "test_rename_field_foreign_key_to_field (migrations.test_autodetector.AutodetectorTests)", "RenameField is used if a field is renamed and db_column equal to the", "test_rename_field_with_renamed_model (migrations.test_autodetector.AutodetectorTests)", "test_rename_foreign_object_fields (migrations.test_autodetector.AutodetectorTests)", "test_rename_index_together_to_index (migrations.test_autodetector.AutodetectorTests)", "test_rename_index_together_to_index_extra_options (migrations.test_autodetector.AutodetectorTests)", "test_rename_index_together_to_index_order_fields (migrations.test_autodetector.AutodetectorTests)", "test_rename_indexes (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of renamed models that are used in M2M relations as", "Tests autodetection of renamed models.", "Model name is case-insensitive. Changing case doesn't lead to any", "The migration to rename a model pointed to by a foreign key in another", "#24537 - The order of fields in a model does not influence", "Tests autodetection of renamed models while simultaneously renaming one", "test_rename_referenced_primary_key (migrations.test_autodetector.AutodetectorTests)", "test_rename_related_field_preserved_db_column (migrations.test_autodetector.AutodetectorTests)", "test_renamed_referenced_m2m_model_case (migrations.test_autodetector.AutodetectorTests)", "#22300 - Adding an FK in the same \"spot\" as a deleted CharField should", "A migration with a FK between two models of the same app does", "#22275 - A migration with circular FK dependency does not try", "A migration with a FK between two models of the same app", "Setting order_with_respect_to adds a field.", "test_set_alter_order_with_respect_to_index_constraint_foo_together (migrations.test_autodetector.AutodetectorTests)", "test_supports_functools_partial (migrations.test_autodetector.AutodetectorTests)", "test_swappable (migrations.test_autodetector.AutodetectorTests)", "test_swappable_changed (migrations.test_autodetector.AutodetectorTests)", "test_swappable_circular_multi_mti (migrations.test_autodetector.AutodetectorTests)", "Swappable models get their CreateModel first.", "test_swappable_lowercase (migrations.test_autodetector.AutodetectorTests)", "test_swappable_many_to_many_model_case (migrations.test_autodetector.AutodetectorTests)", "Trim does not remove dependencies but does remove unwanted apps.", "The autodetector correctly deals with managed models.", "#23415 - The autodetector must correctly deal with custom FK on", "test_unmanaged_delete (migrations.test_autodetector.AutodetectorTests)", "test_unmanaged_to_managed (migrations.test_autodetector.AutodetectorTests)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django__django-12113
within 1st neigbour of last one in stracktrace need to think about path of files also just than file name but can the LLM do that for us?
1
django/db/backends/sqlite3/creation.py
django/django
62254c5202e80a68f4fe6572a2be46a3d953de1a
diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py --- a/django/db/backends/sqlite3/creation.py +++ b/django/db/backends/sqlite3/creation.py @@ -98,4 +98,6 @@ def test_db_signature(self): sig = [self.connection.settings_dict['NAME']] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) + else: + sig.append(test_database_name) return tuple(sig)
diff --git a/tests/backends/sqlite/test_creation.py b/tests/backends/sqlite/test_creation.py new file mode 100644 --- /dev/null +++ b/tests/backends/sqlite/test_creation.py @@ -0,0 +1,18 @@ +import copy +import unittest + +from django.db import connection +from django.test import SimpleTestCase + + +@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') +class TestDbSignatureTests(SimpleTestCase): + def test_custom_test_name(self): + saved_settings = copy.deepcopy(connection.settings_dict) + try: + connection.settings_dict['NAME'] = None + connection.settings_dict['TEST']['NAME'] = 'custom.sqlite.db' + signature = connection.creation.test_db_signature() + self.assertEqual(signature, (None, 'custom.sqlite.db')) + finally: + connection.settings_dict = saved_settings
admin_views.test_multidb fails with persistent test SQLite database. Description (last modified by Mariusz Felisiak) I've tried using persistent SQLite databases for the tests (to make use of --keepdb), but at least some test fails with: sqlite3.OperationalError: database is locked This is not an issue when only using TEST["NAME"] with "default" (which is good enough in terms of performance). diff --git i/tests/test_sqlite.py w/tests/test_sqlite.py index f1b65f7d01..9ce4e32e14 100644 --- i/tests/test_sqlite.py +++ w/tests/test_sqlite.py @@ -15,9 +15,15 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_default.sqlite3' + }, }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_other.sqlite3' + }, } } % tests/runtests.py admin_views.test_multidb -v 3 --keepdb --parallel 1 … Operations to perform: Synchronize unmigrated apps: admin_views, auth, contenttypes, messages, sessions, staticfiles Apply all migrations: admin, sites Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application auth Running pre-migrate handlers for application sites Running pre-migrate handlers for application sessions Running pre-migrate handlers for application admin Running pre-migrate handlers for application admin_views Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Running post-migrate handlers for application contenttypes Running post-migrate handlers for application auth Running post-migrate handlers for application sites Running post-migrate handlers for application sessions Running post-migrate handlers for application admin Running post-migrate handlers for application admin_views System check identified no issues (0 silenced). ERROR ====================================================================== ERROR: setUpClass (admin_views.test_multidb.MultiDatabaseTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked The above exception was the direct cause of the following exception: Traceback (most recent call last): File "…/Vcs/django/django/test/testcases.py", line 1137, in setUpClass cls.setUpTestData() File "…/Vcs/django/tests/admin_views/test_multidb.py", line 40, in setUpTestData username='admin', password='something', email='test@test.org', File "…/Vcs/django/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "…/Vcs/django/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "…/Vcs/django/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "…/Vcs/django/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "…/Vcs/django/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "…/Vcs/django/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "…/Vcs/django/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "…/Vcs/django/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "…/Vcs/django/django/db/models/query.py", line 1175, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "…/Vcs/django/django/db/models/sql/compiler.py", line 1321, in execute_sql cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "…/Vcs/django/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: database is locked
This is only an issue when setting TEST["NAME"], but not NAME. The following works: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_default.sqlite3', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_other.sqlite3', } } Reproduced at 0dd2308cf6f559a4f4b50edd7c005c7cf025d1aa. Created ​PR Hey, I am able to replicate this bug and was able to fix it as well with the help of ​https://github.com/django/django/pull/11678, but the point I am stuck at is how to test it, I am not able to manipulate the cls variable so the next option that is left is create a file like test_sqlite and pass it as a parameter in runtests, should I be doing that? I think we should add tests/backends/sqlite/test_creation.py with regressions tests for test_db_signature(), you can take a look at tests/backends/base/test_creation.py with similar tests.
2019-11-20T17:49:06Z
3.1
["test_custom_test_name (backends.sqlite.test_creation.TestDbSignatureTests)"]
[]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django__django-11620
quite difficult to identify file as debug.py
null
django/views/debug.py
django/django
514efa3129792ec2abb2444f3e7aeb3f21a38386
diff --git a/django/views/debug.py b/django/views/debug.py --- a/django/views/debug.py +++ b/django/views/debug.py @@ -5,10 +5,10 @@ from pathlib import Path from django.conf import settings -from django.http import HttpResponse, HttpResponseNotFound +from django.http import Http404, HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import pprint -from django.urls import Resolver404, resolve +from django.urls import resolve from django.utils import timezone from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str @@ -483,7 +483,7 @@ def technical_404_response(request, exception): caller = '' try: resolver_match = resolve(request.path) - except Resolver404: + except Http404: pass else: obj = resolver_match.func
diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -12,11 +12,13 @@ from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection +from django.http import Http404 from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import path, reverse +from django.urls.converters import IntConverter from django.utils.functional import SimpleLazyObject from django.utils.safestring import mark_safe from django.views.debug import ( @@ -237,6 +239,11 @@ def test_template_encoding(self): technical_404_response(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding='utf-8') + def test_technical_404_converter_raise_404(self): + with mock.patch.object(IntConverter, 'to_python', side_effect=Http404): + response = self.client.get('/path-post/1/') + self.assertContains(response, 'Page not found', status_code=404) + class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection
When DEBUG is True, raising Http404 in a path converter's to_python method does not result in a technical response Description This is the response I get (plain text): A server error occurred. Please contact the administrator. I understand a ValueError should be raised which tells the URL resolver "this path does not match, try next one" but Http404 is what came to my mind intuitively and the error message was not very helpful. One could also make a point that raising a Http404 should be valid way to tell the resolver "this is indeed the right path but the current parameter value does not match anything so stop what you are doing and let the handler return the 404 page (including a helpful error message when DEBUG is True instead of the default 'Django tried these URL patterns')". This would prove useful for example to implement a path converter that uses get_object_or_404.
It seems that other exceptions correctly result in a technical 500 response. The technical_404_response view performs a new URL resolving (cf ​https://github.com/django/django/blob/a8e492bc81fca829f5d270e2d57703c02e58701e/django/views/debug.py#L482) which will obviously raise a new Http404 which won't be caught as only Resolver404 is checked. That means the WSGI handler fails and the WSGI server returns the previously described default error message (indeed the error message is the default one from wsgiref.handlers.BaseHandler ​https://docs.python.org/3.6/library/wsgiref.html#wsgiref.handlers.BaseHandler.error_body). The solution seems to be to catch Http404 instead of Resolver404 in technical_404_response. This will result in a technical 404 page with the Http404's message displayed and will match the behaviour of when DEBUG is False. Created ​PR , but I am not sure how to write the tests. I've looking about the response before and after catch Http404 instead of Resolver404, and there is no difference. Should I also change the technical_404.html for response? I've added test to the patch, but not sure if it is correct. I have made the requested changes; please review again
2019-08-02T13:56:08Z
3.0
["test_technical_404_converter_raise_404 (view_tests.tests.test_debug.DebugViewTests)"]
["test_repr (view_tests.tests.test_debug.CallableSettingWrapperTests)", "test_cleanse_setting_basic (view_tests.tests.test_debug.HelperFunctionTests)", "test_cleanse_setting_ignore_case (view_tests.tests.test_debug.HelperFunctionTests)", "test_cleanse_setting_recurses_in_dictionary (view_tests.tests.test_debug.HelperFunctionTests)", "test_handle_db_exception (view_tests.tests.test_debug.DebugViewQueriesAllowedTests)", "test_400 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)", "test_403 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)", "test_404 (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)", "test_template_not_found_error (view_tests.tests.test_debug.NonDjangoTemplatesDebugViewTests)", "An exception report can be generated even for a disallowed host.", "test_message_only (view_tests.tests.test_debug.PlainTextReportTests)", "An exception report can be generated for just a request", "An exception report can be generated without request", "A simple exception report can be generated", "A message can be provided in addition to a request", "test_request_with_items_key (view_tests.tests.test_debug.PlainTextReportTests)", "test_template_exception (view_tests.tests.test_debug.PlainTextReportTests)", "test_ajax_response_encoding (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)", "test_custom_exception_reporter_filter (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)", "test_non_sensitive_request (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)", "test_paranoid_request (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)", "test_sensitive_request (view_tests.tests.test_debug.AjaxResponseExceptionReporterFilter)", "test_400 (view_tests.tests.test_debug.DebugViewTests)", "test_403 (view_tests.tests.test_debug.DebugViewTests)", "test_403_template (view_tests.tests.test_debug.DebugViewTests)", "test_404 (view_tests.tests.test_debug.DebugViewTests)", "test_404_empty_path_not_in_urls (view_tests.tests.test_debug.DebugViewTests)", "test_404_not_in_urls (view_tests.tests.test_debug.DebugViewTests)", "test_classbased_technical_404 (view_tests.tests.test_debug.DebugViewTests)", "test_default_urlconf_template (view_tests.tests.test_debug.DebugViewTests)", "test_files (view_tests.tests.test_debug.DebugViewTests)", "test_no_template_source_loaders (view_tests.tests.test_debug.DebugViewTests)", "test_non_l10ned_numeric_ids (view_tests.tests.test_debug.DebugViewTests)", "test_regression_21530 (view_tests.tests.test_debug.DebugViewTests)", "test_technical_404 (view_tests.tests.test_debug.DebugViewTests)", "test_template_encoding (view_tests.tests.test_debug.DebugViewTests)", "test_template_exceptions (view_tests.tests.test_debug.DebugViewTests)", "Tests for not existing file", "test_encoding_error (view_tests.tests.test_debug.ExceptionReporterTests)", "The ExceptionReporter supports Unix, Windows and Macintosh EOL markers", "test_exception_fetching_user (view_tests.tests.test_debug.ExceptionReporterTests)", "test_ignore_traceback_evaluation_exceptions (view_tests.tests.test_debug.ExceptionReporterTests)", "Safe strings in local variables are escaped.", "test_message_only (view_tests.tests.test_debug.ExceptionReporterTests)", "Non-UTF-8 exceptions/values should not make the output generation choke.", "test_reporting_frames_for_cyclic_reference (view_tests.tests.test_debug.ExceptionReporterTests)", "test_reporting_frames_without_source (view_tests.tests.test_debug.ExceptionReporterTests)", "test_reporting_of_nested_exceptions (view_tests.tests.test_debug.ExceptionReporterTests)", "test_request_with_items_key (view_tests.tests.test_debug.ExceptionReporterTests)", "test_template_encoding (view_tests.tests.test_debug.ExceptionReporterTests)", "Large values should not create a large HTML.", "test_unfrozen_importlib (view_tests.tests.test_debug.ExceptionReporterTests)", "Unprintable values should not make the output generation choke.", "test_callable_settings (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_callable_settings_forbidding_to_set_attributes (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_custom_exception_reporter_filter (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_dict_setting_with_non_str_key (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_multivalue_dict_key_error (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_non_sensitive_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_paranoid_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_sensitive_function_arguments (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_sensitive_function_keyword_arguments (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_sensitive_method (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_sensitive_request (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_sensitive_settings (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_settings_with_sensitive_keys (view_tests.tests.test_debug.ExceptionReporterFilterTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django__django-16041
need to identify that issue is with empty_form (file, function or class)
0
django/forms/formsets.py
django/django
6df9398cce063874ae4d59db126d4adacb0fa8d3
diff --git a/django/forms/formsets.py b/django/forms/formsets.py --- a/django/forms/formsets.py +++ b/django/forms/formsets.py @@ -257,14 +257,15 @@ def extra_forms(self): @property def empty_form(self): - form = self.form( - auto_id=self.auto_id, - prefix=self.add_prefix("__prefix__"), - empty_permitted=True, - use_required_attribute=False, + form_kwargs = { **self.get_form_kwargs(None), - renderer=self.renderer, - ) + "auto_id": self.auto_id, + "prefix": self.add_prefix("__prefix__"), + "empty_permitted": True, + "use_required_attribute": False, + "renderer": self.renderer, + } + form = self.form(**form_kwargs) self.add_fields(form, None) return form
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -179,6 +179,10 @@ def test_form_kwargs_empty_form(self): self.assertTrue(hasattr(formset.empty_form, "custom_kwarg")) self.assertEqual(formset.empty_form.custom_kwarg, 1) + def test_empty_permitted_ignored_empty_form(self): + formset = ArticleFormSet(form_kwargs={"empty_permitted": False}) + self.assertIs(formset.empty_form.empty_permitted, True) + def test_formset_validation(self): # FormSet instances can also have an error attribute if validation failed for # any of the forms.
Rendering empty_form crashes when empty_permitted is passed to form_kwargs Description Issue When explicitly setting form_kwargs = {'empty_permitted':True} or form_kwargs = {'empty_permitted':False} , a KeyError occurs when rendering a template that uses a formset's empty_form. Expected Behavior empty_permitted is ignored for formset.empty_form since empty_permitted is irrelevant for empty_form, as empty_form is not meant to be used to pass data and therefore does not need to be validated. Steps to Reproduce # views.py from django.shortcuts import render from .models import MyModel def test_view(request): context = {} ff = modelformset_factory(MyModel, fields = ['a_field']) context['formset'] = ff( queryset = MyModel.objects.none(), form_kwargs = {'empty_permitted':True} # or form_kwargs = {'empty_permitted':False} ) return render(request, 'my_app/my_model_formset.html', context) # urls.py from django.urls import path, include from .views import test_view urlpatterns = [ path('test', test_view) ] # my_model_formset.html {% extends "my_app/base.html" %} {% block content %} <form id="my-form" method="post"> {% csrf_token %} {{ formset }} <input type="submit" value="Save"> </form> {{ formset.empty_form }} {% endblock %}
Thanks for the report. It should be enough to change form_kwargs for empty_form, e.g. django/forms/formsets.py diff --git a/django/forms/formsets.py b/django/forms/formsets.py index 57676428ff..b73d1d742e 100644 a b class BaseFormSet(RenderableFormMixin): 257257 258258 @property 259259 def empty_form(self): 260 form = self.form( 261 auto_id=self.auto_id, 262 prefix=self.add_prefix("__prefix__"), 263 empty_permitted=True, 264 use_required_attribute=False, 260 form_kwargs = { 265261 **self.get_form_kwargs(None), 266 renderer=self.renderer, 267 ) 262 "auto_id": self.auto_id, 263 "prefix": self.add_prefix("__prefix__"), 264 "use_required_attribute": False, 265 "empty_permitted": True, 266 "renderer": self.renderer, 267 } 268 form = self.form(**form_kwargs) 268269 self.add_fields(form, None) 269270 return form 270271 Would you like to prepare a patch? (a regression test is required) The KeyError is confusing here. It's raised because we're in the context of rendering the template: >>> self.form(empty_permitted=True, **self.get_form_kwargs(None)) Traceback (most recent call last): File "/Users/carlton/Projects/Django/django/django/template/base.py", line 880, in _resolve_lookup current = current[bit] File "/Users/carlton/Projects/Django/django/django/forms/formsets.py", line 118, in __getitem__ return self.forms[index] TypeError: list indices must be integers or slices, not str During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> KeyError: 'empty_permitted' The real exception is better seen using the formset directly: >>> from ticket_33995.models import MyModel >>> from django.forms import modelformset_factory >>> ff = modelformset_factory(MyModel, fields=['name']) >>> formset = ff(queryset=MyModel.objects.none(), form_kwargs={'empty_permitted': True}) >>> formset.empty_form > /Users/carlton/Projects/Django/django/django/forms/formsets.py(262)empty_form() -> form_kwargs = self.get_form_kwargs(None) (Pdb) c Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/carlton/Projects/Django/django/django/forms/formsets.py", line 265, in empty_form form = self.form( TypeError: django.forms.widgets.MyModelForm() got multiple values for keyword argument 'empty_permitted' That's expected: >>> class Example: ... def __init__(self, a_kwarg=None): ... pass ... >>> Example(a_kwarg=True) <__main__.Example object at 0x102352950> >>> Example(a_kwarg=True, a_kwarg=False) File "<stdin>", line 1 SyntaxError: keyword argument repeated: a_kwarg >>> {"a":1, **{"a":2}} {'a': 2} >>> Example(a_kwarg=True, **{"a_kwarg": False}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __main__.Example() got multiple values for keyword argument 'a_kwarg' Resolving the kwargs before the constructor call, as per Mariusz' suggestion would resolve. #21501 was on a similar topic.
2022-09-09T10:07:29Z
4.2
["test_empty_permitted_ignored_empty_form (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_empty_permitted_ignored_empty_form (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)"]
["all_valid() validates all forms, even when some are invalid.", "test_valid (forms_tests.tests.test_formsets.AllValidTests)", "is_multipart() works with an empty formset.", "An empty formset still calls clean()", "Media is available on empty formset.", "Management forms are already rendered with the new div template.", "test_warning (forms_tests.tests.test_formsets.DeprecationTests)", "test_as_div (forms_tests.tests.test_formsets.FormsetAsTagTests)", "test_as_p (forms_tests.tests.test_formsets.FormsetAsTagTests)", "test_as_table (forms_tests.tests.test_formsets.FormsetAsTagTests)", "test_as_ul (forms_tests.tests.test_formsets.FormsetAsTagTests)", "test_customize_management_form_error (forms_tests.tests.test_formsets.TestIsBoundBehavior)", "test_empty_forms_are_unbound (forms_tests.tests.test_formsets.TestIsBoundBehavior)", "test_form_errors_are_caught_by_formset (forms_tests.tests.test_formsets.TestIsBoundBehavior)", "test_management_form_invalid_data (forms_tests.tests.test_formsets.TestIsBoundBehavior)", "test_no_data_error (forms_tests.tests.test_formsets.TestIsBoundBehavior)", "test_with_management_data_attrs_work_fine (forms_tests.tests.test_formsets.TestIsBoundBehavior)", "test_as_div (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)", "test_as_p (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)", "test_as_table (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)", "test_as_ul (forms_tests.tests.test_formsets.Jinja2FormsetAsTagTests)", "test_absolute_max (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_absolute_max_invalid (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_absolute_max_with_max_num (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "A FormSet constructor takes the same arguments as Form. Create a", "A form that's displayed as blank may be submitted as blank.", "test_can_delete_extra_formset_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "FormSets have a clean() hook for doing extra validation that isn't tied", "A custom renderer passed to a formset_factory() is passed to all forms", "test_default_absolute_max (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "Deleting prefilled data is an error. Removing data from form fields", "test_disable_delete_extra_formset_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "More than 1 empty form can be displayed using formset_factory's", "Ordering fields are allowed to be left blank. If they are left blank,", "test_form_kwargs_empty_form (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "Custom kwargs set on the formset instance are passed to the", "Form kwargs can be passed dynamically in a formset.", "Formsets call is_valid() on each form.", "Formset's forms use the formset's error_class.", "FormSet.has_changed() is True if any data is passed to its forms, even", "A FormSet can be prefilled with existing data by providing a list of", "Formset instances are iterable.", "A formsets without any forms evaluates as True.", "Formset works with SplitDateTimeField(initial=datetime.datetime.now).", "A valid formset should have 0 total errors.", "test_formset_total_error_count_with_non_form_errors (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "If validate_max is set and max_num is less than TOTAL_FORMS in the", "test_formset_validate_max_flag_custom_error (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_formset_validate_min_excludes_empty_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "If validate_min is set and min_num is more than TOTAL_FORMS in the", "test_formset_validate_min_flag_custom_formatted_error (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "min_num validation doesn't consider unchanged forms with initial data", "test_formset_validation (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "A formset's ManagementForm is validated once per FormSet.is_valid()", "formset_factory's can_delete argument adds a boolean \"delete\" field to", "test_formset_with_deletion_custom_widget (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "deleted_forms works on a valid formset even if a deleted form would", "If a form is filled with something and can_delete is also checked, that", "FormSets with ordering + deletion.", "formset_factory's can_order argument adds an integer field to each", "test_formsets_with_ordering_custom_widget (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "A formset has a hard limit on the number of forms instantiated.", "test_html_safe (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "Can increase the built-in forms limit via a higher max_num.", "Can get ordered_forms from a valid formset even if a deleted form", "test_limited_max_forms_two (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "max_num has no effect when extra is less than max_num.", "Limiting the maximum number of forms with max_num.", "The management form class has field names matching the constants.", "The management form has the correct prefix.", "test_max_num_with_initial_data (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "If max_num is 0 then no form is rendered at all, regardless of extra,", "test_max_num_zero_with_initial (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "More than 1 empty form can also be displayed using formset_factory's", "More than 1 empty form can be displayed using min_num.", "The extra argument works when the formset is pre-filled with initial", "One form from initial and extra=3 with max_num=2 results in the one", "More initial forms than max_num results in all initial forms being", "test_non_form_errors (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "If non_form_errors() is called without calling is_valid() first,", "Ordering works with blank fieldsets.", "test_repr (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_repr_do_not_trigger_validation (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "If at least one field is filled out on a blank form, it will be", "A partially completed form is invalid.", "Just one form may be completed.", "test_template_name_can_be_overridden (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_template_name_uses_renderer_value (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_validate_max_ignores_forms_marked_for_deletion (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_absolute_max (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_absolute_max_invalid (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_absolute_max_with_max_num (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_can_delete_extra_formset_forms (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_default_absolute_max (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_disable_delete_extra_formset_forms (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_form_kwargs_empty_form (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_formset_total_error_count_with_non_form_errors (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_formset_validate_max_flag_custom_error (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_formset_validate_min_excludes_empty_forms (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_formset_validate_min_flag_custom_formatted_error (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_formset_validation (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_formset_with_deletion_custom_widget (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_formsets_with_ordering_custom_widget (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_html_safe (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_limited_max_forms_two (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_max_num_with_initial_data (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_max_num_zero_with_initial (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_non_form_errors (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_repr (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_repr_do_not_trigger_validation (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_template_name_can_be_overridden (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_template_name_uses_renderer_value (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)", "test_validate_max_ignores_forms_marked_for_deletion (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django__django-13033
Difficult to identify but can get an idea with sql statements and by considering file formats
null
django/db/models/sql/compiler.py
django/django
a59de6e89e8dc1f3e71c9a5a5bbceb373ea5247e
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -727,7 +727,12 @@ def find_ordering_name(self, name, opts, alias=None, default_order='ASC', # 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. - if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name and name != 'pk': + if ( + field.is_relation and + opts.ordering and + getattr(field, 'attname', None) != pieces[-1] and + name != 'pk' + ): # 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)
diff --git a/tests/ordering/models.py b/tests/ordering/models.py --- a/tests/ordering/models.py +++ b/tests/ordering/models.py @@ -18,6 +18,7 @@ class Author(models.Model): name = models.CharField(max_length=63, null=True, blank=True) + editor = models.ForeignKey('self', models.CASCADE, null=True) class Meta: ordering = ('-pk',) diff --git a/tests/ordering/tests.py b/tests/ordering/tests.py --- a/tests/ordering/tests.py +++ b/tests/ordering/tests.py @@ -343,6 +343,22 @@ def test_order_by_fk_attname(self): attrgetter("headline") ) + def test_order_by_self_referential_fk(self): + self.a1.author = Author.objects.create(editor=self.author_1) + self.a1.save() + self.a2.author = Author.objects.create(editor=self.author_2) + self.a2.save() + self.assertQuerysetEqual( + Article.objects.filter(author__isnull=False).order_by('author__editor'), + ['Article 2', 'Article 1'], + attrgetter('headline'), + ) + self.assertQuerysetEqual( + Article.objects.filter(author__isnull=False).order_by('author__editor_id'), + ['Article 1', 'Article 2'], + attrgetter('headline'), + ) + def test_order_by_f_expression(self): self.assertQuerysetEqual( Article.objects.order_by(F('headline')), [
Self referencing foreign key doesn't correctly order by a relation "_id" field. Description Initially discovered on 2.2.10 but verified still happens on 3.0.6. Given the following models: class OneModel(models.Model): class Meta: ordering = ("-id",) id = models.BigAutoField(primary_key=True) root = models.ForeignKey("OneModel", on_delete=models.CASCADE, null=True) oneval = models.BigIntegerField(null=True) class TwoModel(models.Model): id = models.BigAutoField(primary_key=True) record = models.ForeignKey(OneModel, on_delete=models.CASCADE) twoval = models.BigIntegerField(null=True) The following queryset gives unexpected results and appears to be an incorrect SQL query: qs = TwoModel.objects.filter(record__oneval__in=[1,2,3]) qs = qs.order_by("record__root_id") print(qs.query) SELECT "orion_twomodel"."id", "orion_twomodel"."record_id", "orion_twomodel"."twoval" FROM "orion_twomodel" INNER JOIN "orion_onemodel" ON ("orion_twomodel"."record_id" = "orion_onemodel"."id") LEFT OUTER JOIN "orion_onemodel" T3 ON ("orion_onemodel"."root_id" = T3."id") WHERE "orion_onemodel"."oneval" IN (1, 2, 3) ORDER BY T3."id" DESC The query has an unexpected DESCENDING sort. That appears to come from the default sort order on the OneModel class, but I would expect the order_by() to take prececence. The the query has two JOINS, which is unnecessary. It appears that, since OneModel.root is a foreign key to itself, that is causing it to do the unnecessary extra join. In fact, testing a model where root is a foreign key to a third model doesn't show the problem behavior. Note also that the queryset with order_by("record__root") gives the exact same SQL. This queryset gives correct results and what looks like a pretty optimal SQL: qs = TwoModel.objects.filter(record__oneval__in=[1,2,3]) qs = qs.order_by("record__root__id") print(qs.query) SELECT "orion_twomodel"."id", "orion_twomodel"."record_id", "orion_twomodel"."twoval" FROM "orion_twomodel" INNER JOIN "orion_onemodel" ON ("orion_twomodel"."record_id" = "orion_onemodel"."id") WHERE "orion_onemodel"."oneval" IN (1, 2, 3) ORDER BY "orion_onemodel"."root_id" ASC So is this a potential bug or a misunderstanding on my part? Another queryset that works around the issue and gives a reasonable SQL query and expected results: qs = TwoModel.objects.filter(record__oneval__in=[1,2,3]) qs = qs.annotate(root_id=F("record__root_id")) qs = qs.order_by("root_id") print(qs.query) SELECT "orion_twomodel"."id", "orion_twomodel"."record_id", "orion_twomodel"."twoval" FROM "orion_twomodel" INNER JOIN "orion_onemodel" ON ("orion_twomodel"."record_id" = "orion_onemodel"."id") WHERE "orion_onemodel"."oneval" IN (1, 2, 3) ORDER BY "orion_onemodel"."zero_id" ASC ASCENDING sort, and a single INNER JOIN, as I'd expect. That actually works for my use because I need that output column anyway. One final oddity; with the original queryset but the inverted sort order_by(): qs = TwoModel.objects.filter(record__oneval__in=[1,2,3]) qs = qs.order_by("-record__root_id") print(qs.query) SELECT "orion_twomodel"."id", "orion_twomodel"."record_id", "orion_twomodel"."twoval" FROM "orion_twomodel" INNER JOIN "orion_onemodel" ON ("orion_twomodel"."record_id" = "orion_onemodel"."id") LEFT OUTER JOIN "orion_onemodel" T3 ON ("orion_onemodel"."root_id" = T3."id") WHERE "orion_onemodel"."oneval" IN (1, 2, 3) ORDER BY T3."id" ASC One gets the query with the two JOINs but an ASCENDING sort order. I was not under the impression that sort orders are somehow relative to the class level sort order, eg: does specifing order_by("-record__root_id") invert the class sort order? Testing that on a simple case doesn't show that behavior at all. Thanks for any assistance and clarification.
This is with a postgres backend. Fairly vanilla Django. Some generic middleware installed (cors, csrf, auth, session). Apps are: INSTALLED_APPS = ( "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.admin", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", "<ours>" ) Something is definitely wrong here. order_by('record__root_id') should result in ORDER BY root_id order_by('record__root') should use OneModel.Meta.ordering because that's what the root foreign key points to ​as documented. That should result in ORDER BY root_join.id DESC order_by('record__root__id') should result in ORDER BY root_join.id Thanks for this report. A potential fix could be: diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index abbb1e37cb..a8f5b61fbe 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -727,7 +727,7 @@ class SQLCompiler: # 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. - if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name and name != 'pk': + if field.is_relation and opts.ordering and getattr(field, 'attname', None) != pieces[-1] and name != 'pk': # 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) but I didn't check this in details. FWIW, I did apply the suggested fix to my local version and I do now get what looks like correct behavior and results that match what Simon suggested should be the sort results. Also my annotate "workaround" continues to behave correctly. Looks promising. Jack, would you like to prepare a patch? ​PR I did some additional work on this to verify the scope of the change. I added the following test code on master and ran the entire test suite: +++ b/django/db/models/sql/compiler.py @@ -727,6 +727,11 @@ class SQLCompiler: # 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. + if (field.is_relation and opts.ordering and name != 'pk' and + ((getattr(field, 'attname', None) != name) != + (getattr(field, 'attname', None) != pieces[-1]))): + print(f"JJD <{getattr(field, 'attname', '')}> <{name}> <{pieces[-1]}>") + breakpoint() if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name and name != 'pk': # Firstly, avoid infinite loops. already_seen = already_seen or set() The idea being to display every time that the change from name to pieces[-1] in the code would make a difference in the execution. Of course verified that when running the reproducer one does go into the test block and outputs: JJD <root_id> <record__root_id> <root_id>. The code is not triggered for any other test across the entire test suite, so the scope of the change is not causing unexpected changes in other places. This seems reassuring.
2020-06-07T14:52:19Z
3.2
["test_order_by_self_referential_fk (ordering.tests.OrderingTests)"]
["test_default_ordering (ordering.tests.OrderingTests)", "F expressions can be used in Meta.ordering.", "test_default_ordering_override (ordering.tests.OrderingTests)", "test_extra_ordering (ordering.tests.OrderingTests)", "test_extra_ordering_quoting (ordering.tests.OrderingTests)", "test_extra_ordering_with_table_name (ordering.tests.OrderingTests)", "test_no_reordering_after_slicing (ordering.tests.OrderingTests)", "test_order_by_constant_value (ordering.tests.OrderingTests)", "test_order_by_constant_value_without_output_field (ordering.tests.OrderingTests)", "test_order_by_f_expression (ordering.tests.OrderingTests)", "test_order_by_f_expression_duplicates (ordering.tests.OrderingTests)", "test_order_by_fk_attname (ordering.tests.OrderingTests)", "test_order_by_nulls_first (ordering.tests.OrderingTests)", "test_order_by_nulls_first_and_last (ordering.tests.OrderingTests)", "test_order_by_nulls_last (ordering.tests.OrderingTests)", "test_order_by_override (ordering.tests.OrderingTests)", "test_order_by_pk (ordering.tests.OrderingTests)", "test_order_by_ptr_field_with_default_ordering_by_expression (ordering.tests.OrderingTests)", "test_orders_nulls_first_on_filtered_subquery (ordering.tests.OrderingTests)", "test_random_ordering (ordering.tests.OrderingTests)", "test_related_ordering_duplicate_table_reference (ordering.tests.OrderingTests)", "test_reverse_meta_ordering_pure (ordering.tests.OrderingTests)", "test_reverse_ordering_pure (ordering.tests.OrderingTests)", "test_reversed_ordering (ordering.tests.OrderingTests)", "test_stop_slicing (ordering.tests.OrderingTests)", "test_stop_start_slicing (ordering.tests.OrderingTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django__django-14411
need to identify ReadOnlyPasswordHashWidget
0
django/contrib/auth/forms.py
django/django
fa4e963ee7e6876581b5432363603571839ba00c
diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -50,6 +50,9 @@ def get_context(self, name, value, attrs): context['summary'] = summary return context + def id_for_label(self, id_): + return None + class ReadOnlyPasswordHashField(forms.Field): widget = ReadOnlyPasswordHashWidget
diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py --- a/tests/auth_tests/test_forms.py +++ b/tests/auth_tests/test_forms.py @@ -13,6 +13,7 @@ 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.utils import translation @@ -1025,6 +1026,18 @@ def test_readonly_field_has_changed(self): 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.assertEqual(bound_field.field.widget.id_for_label('id'), None) + self.assertEqual(bound_field.label_tag(), '<label>Hash field:</label>') + class AdminPasswordChangeFormTest(TestDataMixin, TestCase):
Label for ReadOnlyPasswordHashWidget points to non-labelable element. Description (last modified by David Sanders) In the admin, the label element for the ReadOnlyPasswordHashWidget widget has a 'for' attribute which points to a non-labelable element, since the widget just renders text, not an input. There's no labelable element for the widget, so the label shouldn't have a 'for' attribute.
2021-05-19T04:05:47Z
4.0
["ReadOnlyPasswordHashWidget doesn't contain a for attribute in the"]
["test_html_autocomplete_attributes (auth_tests.test_forms.AdminPasswordChangeFormTest)", "test_missing_passwords (auth_tests.test_forms.AdminPasswordChangeFormTest)", "test_non_matching_passwords (auth_tests.test_forms.AdminPasswordChangeFormTest)", "test_one_password (auth_tests.test_forms.AdminPasswordChangeFormTest)", "test_password_whitespace_not_stripped (auth_tests.test_forms.AdminPasswordChangeFormTest)", "test_success (auth_tests.test_forms.AdminPasswordChangeFormTest)", "test_field_order (auth_tests.test_forms.PasswordChangeFormTest)", "test_html_autocomplete_attributes (auth_tests.test_forms.PasswordChangeFormTest)", "test_incorrect_password (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_verification (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_whitespace_not_stripped (auth_tests.test_forms.PasswordChangeFormTest)", "test_success (auth_tests.test_forms.PasswordChangeFormTest)", "test_both_passwords (auth_tests.test_forms.UserCreationFormTest)", "test_custom_form (auth_tests.test_forms.UserCreationFormTest)", "test_custom_form_hidden_username_field (auth_tests.test_forms.UserCreationFormTest)", "test_custom_form_with_different_username_field (auth_tests.test_forms.UserCreationFormTest)", "To prevent almost identical usernames, visually identical but differing", "test_html_autocomplete_attributes (auth_tests.test_forms.UserCreationFormTest)", "test_invalid_data (auth_tests.test_forms.UserCreationFormTest)", "test_normalize_username (auth_tests.test_forms.UserCreationFormTest)", "test_password_help_text (auth_tests.test_forms.UserCreationFormTest)", "test_password_verification (auth_tests.test_forms.UserCreationFormTest)", "test_password_whitespace_not_stripped (auth_tests.test_forms.UserCreationFormTest)", "test_success (auth_tests.test_forms.UserCreationFormTest)", "test_unicode_username (auth_tests.test_forms.UserCreationFormTest)", "test_user_already_exists (auth_tests.test_forms.UserCreationFormTest)", "UserCreationForm password validation uses all of the form's data.", "test_username_field_autocapitalize_none (auth_tests.test_forms.UserCreationFormTest)", "test_validates_password (auth_tests.test_forms.UserCreationFormTest)", "test_bug_19349_render_with_none_value (auth_tests.test_forms.ReadOnlyPasswordHashTest)", "test_readonly_field_has_changed (auth_tests.test_forms.ReadOnlyPasswordHashTest)", "test_render (auth_tests.test_forms.ReadOnlyPasswordHashTest)", "test_help_text_translation (auth_tests.test_forms.SetPasswordFormTest)", "test_html_autocomplete_attributes (auth_tests.test_forms.SetPasswordFormTest)", "test_password_verification (auth_tests.test_forms.SetPasswordFormTest)", "test_password_whitespace_not_stripped (auth_tests.test_forms.SetPasswordFormTest)", "test_success (auth_tests.test_forms.SetPasswordFormTest)", "test_validates_password (auth_tests.test_forms.SetPasswordFormTest)", "test_custom_login_allowed_policy (auth_tests.test_forms.AuthenticationFormTest)", "test_get_invalid_login_error (auth_tests.test_forms.AuthenticationFormTest)", "test_html_autocomplete_attributes (auth_tests.test_forms.AuthenticationFormTest)", "test_inactive_user (auth_tests.test_forms.AuthenticationFormTest)", "test_inactive_user_i18n (auth_tests.test_forms.AuthenticationFormTest)", "An invalid login doesn't leak the inactive status of a user.", "test_integer_username (auth_tests.test_forms.AuthenticationFormTest)", "test_invalid_username (auth_tests.test_forms.AuthenticationFormTest)", "test_login_failed (auth_tests.test_forms.AuthenticationFormTest)", "test_password_whitespace_not_stripped (auth_tests.test_forms.AuthenticationFormTest)", "test_success (auth_tests.test_forms.AuthenticationFormTest)", "test_unicode_username (auth_tests.test_forms.AuthenticationFormTest)", "test_username_field_autocapitalize_none (auth_tests.test_forms.AuthenticationFormTest)", "test_username_field_label (auth_tests.test_forms.AuthenticationFormTest)", "test_username_field_label_empty_string (auth_tests.test_forms.AuthenticationFormTest)", "test_username_field_label_not_set (auth_tests.test_forms.AuthenticationFormTest)", "test_username_field_max_length_defaults_to_254 (auth_tests.test_forms.AuthenticationFormTest)", "test_username_field_max_length_matches_user_model (auth_tests.test_forms.AuthenticationFormTest)", "test_cleaned_data (auth_tests.test_forms.PasswordResetFormTest)", "test_custom_email_constructor (auth_tests.test_forms.PasswordResetFormTest)", "test_custom_email_field (auth_tests.test_forms.PasswordResetFormTest)", "test_custom_email_subject (auth_tests.test_forms.PasswordResetFormTest)", "test_html_autocomplete_attributes (auth_tests.test_forms.PasswordResetFormTest)", "Inactive user cannot receive password reset email.", "test_invalid_email (auth_tests.test_forms.PasswordResetFormTest)", "Test nonexistent email address. This should not fail because it would", "Preserve the case of the user name (before the @ in the email address)", "Test the PasswordResetForm.save() method with html_email_template_name", "Test the PasswordResetForm.save() method with no html_email_template_name", "test_unusable_password (auth_tests.test_forms.PasswordResetFormTest)", "test_user_email_domain_unicode_collision (auth_tests.test_forms.PasswordResetFormTest)", "test_user_email_domain_unicode_collision_nonexistent (auth_tests.test_forms.PasswordResetFormTest)", "test_user_email_unicode_collision (auth_tests.test_forms.PasswordResetFormTest)", "test_user_email_unicode_collision_nonexistent (auth_tests.test_forms.PasswordResetFormTest)", "test_bug_14242 (auth_tests.test_forms.UserChangeFormTest)", "test_bug_17944_empty_password (auth_tests.test_forms.UserChangeFormTest)", "test_bug_17944_unknown_password_algorithm (auth_tests.test_forms.UserChangeFormTest)", "test_bug_17944_unmanageable_password (auth_tests.test_forms.UserChangeFormTest)", "The change form does not return the password value", "test_bug_19349_bound_password_field (auth_tests.test_forms.UserChangeFormTest)", "test_custom_form (auth_tests.test_forms.UserChangeFormTest)", "test_password_excluded (auth_tests.test_forms.UserChangeFormTest)", "test_unusable_password (auth_tests.test_forms.UserChangeFormTest)", "test_username_field_autocapitalize_none (auth_tests.test_forms.UserChangeFormTest)", "test_username_validity (auth_tests.test_forms.UserChangeFormTest)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-13447
need to identify function _buil_app_dict. it is quite possible
0
django/contrib/admin/sites.py
django/django
0456d3e42795481a186db05719300691fe2a1029
diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py --- a/django/contrib/admin/sites.py +++ b/django/contrib/admin/sites.py @@ -461,6 +461,7 @@ def _build_app_dict(self, request, label=None): info = (app_label, model._meta.model_name) model_dict = { + 'model': model, 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms,
diff --git a/tests/admin_views/test_adminsite.py b/tests/admin_views/test_adminsite.py --- a/tests/admin_views/test_adminsite.py +++ b/tests/admin_views/test_adminsite.py @@ -55,7 +55,9 @@ def test_available_apps(self): admin_views = apps[0] self.assertEqual(admin_views['app_label'], 'admin_views') self.assertEqual(len(admin_views['models']), 1) - self.assertEqual(admin_views['models'][0]['object_name'], 'Article') + article = admin_views['models'][0] + self.assertEqual(article['object_name'], 'Article') + self.assertEqual(article['model'], Article) # auth.User auth = apps[1] @@ -63,6 +65,7 @@ def test_available_apps(self): self.assertEqual(len(auth['models']), 1) user = auth['models'][0] self.assertEqual(user['object_name'], 'User') + self.assertEqual(user['model'], User) self.assertEqual(auth['app_url'], '/test_admin/admin/auth/') self.assertIs(auth['has_module_perms'], True)
Added model class to app_list context Description (last modified by Raffaele Salmaso) I need to manipulate the app_list in my custom admin view, and the easiest way to get the result is to have access to the model class (currently the dictionary is a serialized model). In addition I would make the _build_app_dict method public, as it is used by the two views index and app_index.
2020-09-22T08:49:25Z
4.0
["test_available_apps (admin_views.test_adminsite.SiteEachContextTest)"]
["test_add_action (admin_views.test_adminsite.SiteActionsTests)", "test_disable_action (admin_views.test_adminsite.SiteActionsTests)", "AdminSite.get_action() returns an action even if it's disabled.", "test_each_context (admin_views.test_adminsite.SiteEachContextTest)", "test_each_context_site_url_with_script_name (admin_views.test_adminsite.SiteEachContextTest)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-12856
check constraint and unique constraints are quite similar and it has given in the description implicitly otherwise difficult to find it
null
django/db/models/base.py
django/django
8328811f048fed0dd22573224def8c65410c9f2e
diff --git a/django/db/models/base.py b/django/db/models/base.py --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -1926,6 +1926,12 @@ def _check_constraints(cls, databases): id='models.W038', ) ) + fields = ( + field + for constraint in cls._meta.constraints if isinstance(constraint, UniqueConstraint) + for field in constraint.fields + ) + errors.extend(cls._check_local_fields(fields, 'constraints')) return errors
diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py --- a/tests/invalid_models_tests/test_models.py +++ b/tests/invalid_models_tests/test_models.py @@ -1501,3 +1501,70 @@ class Meta: ] self.assertEqual(Model.check(databases=self.databases), []) + + def test_unique_constraint_pointing_to_missing_field(self): + class Model(models.Model): + class Meta: + constraints = [models.UniqueConstraint(fields=['missing_field'], name='name')] + + self.assertEqual(Model.check(databases=self.databases), [ + Error( + "'constraints' refers to the nonexistent field " + "'missing_field'.", + obj=Model, + id='models.E012', + ), + ]) + + def test_unique_constraint_pointing_to_m2m_field(self): + class Model(models.Model): + m2m = models.ManyToManyField('self') + + class Meta: + constraints = [models.UniqueConstraint(fields=['m2m'], name='name')] + + self.assertEqual(Model.check(databases=self.databases), [ + Error( + "'constraints' refers to a ManyToManyField 'm2m', but " + "ManyToManyFields are not permitted in 'constraints'.", + obj=Model, + id='models.E013', + ), + ]) + + def test_unique_constraint_pointing_to_non_local_field(self): + class Parent(models.Model): + field1 = models.IntegerField() + + class Child(Parent): + field2 = models.IntegerField() + + class Meta: + constraints = [ + models.UniqueConstraint(fields=['field2', 'field1'], name='name'), + ] + + self.assertEqual(Child.check(databases=self.databases), [ + Error( + "'constraints' refers to field 'field1' which is not local to " + "model 'Child'.", + hint='This issue may be caused by multi-table inheritance.', + obj=Child, + id='models.E016', + ), + ]) + + def test_unique_constraint_pointing_to_fk(self): + class Target(models.Model): + pass + + class Model(models.Model): + fk_1 = models.ForeignKey(Target, models.CASCADE, related_name='target_1') + fk_2 = models.ForeignKey(Target, models.CASCADE, related_name='target_2') + + class Meta: + constraints = [ + models.UniqueConstraint(fields=['fk_1_id', 'fk_2'], name='name'), + ] + + self.assertEqual(Model.check(databases=self.databases), [])
Add check for fields of UniqueConstraints. Description (last modified by Marnanel Thurman) When a model gains a UniqueConstraint, makemigrations doesn't check that the fields named therein actually exist. This is in contrast to the older unique_together syntax, which raises models.E012 if the fields don't exist. In the attached demonstration, you'll need to uncomment "with_unique_together" in settings.py in order to show that unique_together raises E012.
Demonstration Agreed. We can simply call cls._check_local_fields() for UniqueConstraint's fields. I attached tests. Tests. Hello Django Team, My name is Jannah Mandwee, and I am working on my final project for my undergraduate software engineering class (here is the link to the assignment: ​https://web.eecs.umich.edu/~weimerw/481/hw6.html). I have to contribute to an open-source project and was advised to look through easy ticket pickings. I am wondering if it is possible to contribute to this ticket or if there is another ticket you believe would be a better fit for me. Thank you for your help. Replying to Jannah Mandwee: Hello Django Team, My name is Jannah Mandwee, and I am working on my final project for my undergraduate software engineering class (here is the link to the assignment: ​https://web.eecs.umich.edu/~weimerw/481/hw6.html). I have to contribute to an open-source project and was advised to look through easy ticket pickings. I am wondering if it is possible to contribute to this ticket or if there is another ticket you believe would be a better fit for me. Thank you for your help. Hi Jannah, I'm working in this ticket. You can consult this report: https://code.djangoproject.com/query?status=!closed&easy=1&stage=Accepted&order=priority there are all the tickets marked as easy. CheckConstraint might have the same bug.
2020-05-04T21:29:23Z
3.2
["test_unique_constraint_pointing_to_m2m_field (invalid_models_tests.test_models.ConstraintsTests)", "test_unique_constraint_pointing_to_missing_field (invalid_models_tests.test_models.ConstraintsTests)", "test_unique_constraint_pointing_to_non_local_field (invalid_models_tests.test_models.ConstraintsTests)"]
["test_check_jsonfield (invalid_models_tests.test_models.JSONFieldTests)", "test_check_jsonfield_required_db_features (invalid_models_tests.test_models.JSONFieldTests)", "test_ordering_pointing_to_json_field_value (invalid_models_tests.test_models.JSONFieldTests)", "test_db_column_clash (invalid_models_tests.test_models.FieldNamesTests)", "test_ending_with_underscore (invalid_models_tests.test_models.FieldNamesTests)", "test_including_separator (invalid_models_tests.test_models.FieldNamesTests)", "test_pk (invalid_models_tests.test_models.FieldNamesTests)", "test_list_containing_non_iterable (invalid_models_tests.test_models.UniqueTogetherTests)", "test_non_iterable (invalid_models_tests.test_models.UniqueTogetherTests)", "test_non_list (invalid_models_tests.test_models.UniqueTogetherTests)", "test_pointing_to_fk (invalid_models_tests.test_models.UniqueTogetherTests)", "test_pointing_to_m2m (invalid_models_tests.test_models.UniqueTogetherTests)", "test_pointing_to_missing_field (invalid_models_tests.test_models.UniqueTogetherTests)", "test_valid_model (invalid_models_tests.test_models.UniqueTogetherTests)", "test_list_containing_non_iterable (invalid_models_tests.test_models.IndexTogetherTests)", "test_non_iterable (invalid_models_tests.test_models.IndexTogetherTests)", "test_non_list (invalid_models_tests.test_models.IndexTogetherTests)", "test_pointing_to_fk (invalid_models_tests.test_models.IndexTogetherTests)", "test_pointing_to_m2m_field (invalid_models_tests.test_models.IndexTogetherTests)", "test_pointing_to_missing_field (invalid_models_tests.test_models.IndexTogetherTests)", "test_pointing_to_non_local_field (invalid_models_tests.test_models.IndexTogetherTests)", "test_field_name_clash_with_child_accessor (invalid_models_tests.test_models.ShadowingFieldsTests)", "test_id_clash (invalid_models_tests.test_models.ShadowingFieldsTests)", "test_inheritance_clash (invalid_models_tests.test_models.ShadowingFieldsTests)", "test_multigeneration_inheritance (invalid_models_tests.test_models.ShadowingFieldsTests)", "test_multiinheritance_clash (invalid_models_tests.test_models.ShadowingFieldsTests)", "test_index_with_condition (invalid_models_tests.test_models.IndexesTests)", "test_index_with_condition_required_db_features (invalid_models_tests.test_models.IndexesTests)", "test_max_name_length (invalid_models_tests.test_models.IndexesTests)", "test_name_constraints (invalid_models_tests.test_models.IndexesTests)", "test_pointing_to_fk (invalid_models_tests.test_models.IndexesTests)", "test_pointing_to_m2m_field (invalid_models_tests.test_models.IndexesTests)", "test_pointing_to_missing_field (invalid_models_tests.test_models.IndexesTests)", "test_pointing_to_non_local_field (invalid_models_tests.test_models.IndexesTests)", "test_check_constraints (invalid_models_tests.test_models.ConstraintsTests)", "test_check_constraints_required_db_features (invalid_models_tests.test_models.ConstraintsTests)", "test_deferrable_unique_constraint (invalid_models_tests.test_models.ConstraintsTests)", "test_deferrable_unique_constraint_required_db_features (invalid_models_tests.test_models.ConstraintsTests)", "test_unique_constraint_pointing_to_fk (invalid_models_tests.test_models.ConstraintsTests)", "test_unique_constraint_with_condition (invalid_models_tests.test_models.ConstraintsTests)", "test_unique_constraint_with_condition_required_db_features (invalid_models_tests.test_models.ConstraintsTests)", "test_just_order_with_respect_to_no_errors (invalid_models_tests.test_models.OtherModelTests)", "test_just_ordering_no_errors (invalid_models_tests.test_models.OtherModelTests)", "test_lazy_reference_checks (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_autogenerated_table_name_clash (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_autogenerated_table_name_clash_database_routers_installed (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_field_table_name_clash (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_field_table_name_clash_database_routers_installed (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_table_name_clash (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_table_name_clash_database_routers_installed (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_to_concrete_and_proxy_allowed (invalid_models_tests.test_models.OtherModelTests)", "test_m2m_unmanaged_shadow_models_not_checked (invalid_models_tests.test_models.OtherModelTests)", "test_name_beginning_with_underscore (invalid_models_tests.test_models.OtherModelTests)", "test_name_contains_double_underscores (invalid_models_tests.test_models.OtherModelTests)", "test_name_ending_with_underscore (invalid_models_tests.test_models.OtherModelTests)", "test_non_valid (invalid_models_tests.test_models.OtherModelTests)", "test_onetoone_with_explicit_parent_link_parent_model (invalid_models_tests.test_models.OtherModelTests)", "test_onetoone_with_parent_model (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_allows_registered_lookups (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_non_iterable (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_multiple_times_to_model_fields (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_foreignkey_field (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_lookup_not_transform (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_missing_field (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_missing_foreignkey_field (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_missing_related_field (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_missing_related_model_field (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_non_related_field (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_related_model_pk (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_two_related_model_field (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_with_order_with_respect_to (invalid_models_tests.test_models.OtherModelTests)", "test_property_and_related_field_accessor_clash (invalid_models_tests.test_models.OtherModelTests)", "test_single_primary_key (invalid_models_tests.test_models.OtherModelTests)", "test_swappable_missing_app (invalid_models_tests.test_models.OtherModelTests)", "test_swappable_missing_app_name (invalid_models_tests.test_models.OtherModelTests)", "test_two_m2m_through_same_model_with_different_through_fields (invalid_models_tests.test_models.OtherModelTests)", "test_two_m2m_through_same_relationship (invalid_models_tests.test_models.OtherModelTests)", "test_unique_primary_key (invalid_models_tests.test_models.OtherModelTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django__django-14787
file structure is important
null
django/utils/decorators.py
django/django
004b4620f6f4ad87261e149898940f2dcd5757ef
diff --git a/django/utils/decorators.py b/django/utils/decorators.py --- a/django/utils/decorators.py +++ b/django/utils/decorators.py @@ -37,7 +37,7 @@ def _wrapper(self, *args, **kwargs): # 'self' argument, but it's a closure over self so it can call # 'func'. Also, wrap method.__get__() in a function because new # attributes can't be set on bound method objects, only on functions. - bound_method = partial(method.__get__(self, type(self))) + bound_method = wraps(method)(partial(method.__get__(self, type(self)))) for dec in decorators: bound_method = dec(bound_method) return bound_method(*args, **kwargs)
diff --git a/tests/decorators/tests.py b/tests/decorators/tests.py --- a/tests/decorators/tests.py +++ b/tests/decorators/tests.py @@ -425,6 +425,29 @@ class Test: 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): """
method_decorator() should preserve wrapper assignments Description the function that is passed to the decorator is a partial object and does not have any of the attributes expected from a function i.e. __name__, __module__ etc... consider the following case def logger(func): @wraps(func) def inner(*args, **kwargs): try: result = func(*args, **kwargs) except Exception as e: result = str(e) finally: logger.debug(f"{func.__name__} called with args: {args} and kwargs: {kwargs} resulting: {result}") return inner class Test: @method_decorator(logger) def hello_world(self): return "hello" Test().test_method() This results in the following exception AttributeError: 'functools.partial' object has no attribute '__name__'
2021-08-23T12:59:59Z
4.1
["@method_decorator preserves wrapper assignments."]
["test_cache_control_decorator_http_request (decorators.tests.CacheControlDecoratorTest)", "Ensures @xframe_options_deny properly sets the X-Frame-Options header.", "Ensures @xframe_options_exempt properly instructs the", "Ensures @xframe_options_sameorigin properly sets the X-Frame-Options", "Built-in decorators set certain attributes of the wrapped function.", "test_cache_page (decorators.tests.DecoratorsTest)", "Test for the require_safe decorator.", "The user_passes_test decorator can be applied multiple times (#9474).", "test_never_cache_decorator (decorators.tests.NeverCacheDecoratorTest)", "test_never_cache_decorator_http_request (decorators.tests.NeverCacheDecoratorTest)", "test_argumented (decorators.tests.MethodDecoratorTests)", "test_bad_iterable (decorators.tests.MethodDecoratorTests)", "@method_decorator can be used to decorate a class and its methods.", "test_descriptors (decorators.tests.MethodDecoratorTests)", "@method_decorator on a nonexistent method raises an error.", "@method_decorator on a non-callable attribute raises an error.", "A decorator that sets a new attribute on the method.", "test_preserve_attributes (decorators.tests.MethodDecoratorTests)", "test_preserve_signature (decorators.tests.MethodDecoratorTests)", "@method_decorator can accept a tuple of decorators."]
647480166bfe7532e8c471fef0146e3a17e6c0c9
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1