instance_id
stringlengths
20
20
feedback
stringlengths
5
152
level
int64
0
2
erroneous_file
stringlengths
21
49
repo
stringclasses
1 value
base_commit
stringlengths
40
40
patch
stringlengths
386
2.03k
test_patch
stringlengths
488
4.45k
problem_statement
stringlengths
262
4.67k
hints_text
stringlengths
0
9.06k
created_at
stringdate
2019-02-03 11:30:12
2023-02-05 22:05:00
version
stringclasses
7 values
FAIL_TO_PASS
stringlengths
52
310
PASS_TO_PASS
stringlengths
66
11.1k
environment_setup_commit
stringclasses
7 values
django__django-15202
Retreival is straightford correct file is the last stacktrace that has valid path
1
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-14017
Retreival is straightford correct file is the last stacktrace that has valid path
0
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
0
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
0
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
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
1
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-11583
null
0
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-11620
quite difficult to identify file as debug.py
2
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)
1
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
1
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
1
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
1
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
0
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
django__django-11905
only possibility with isnull but it has not followed exact capital sinple format in issue description
0
django/db/models/lookups.py
django/django
2f72480fbd27896c986c45193e1603e35c0b19a7
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 @@ -1,5 +1,6 @@ import itertools import math +import warnings from copy import copy from django.core.exceptions import EmptyResultSet @@ -9,6 +10,7 @@ ) from django.db.models.query_utils import RegisterLookupMixin from django.utils.datastructures import OrderedSet +from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import cached_property @@ -463,6 +465,17 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + # When the deprecation ends, replace with: + # raise ValueError( + # 'The QuerySet value for an isnull lookup must be True or ' + # 'False.' + # ) + warnings.warn( + 'Using a non-boolean value for an isnull lookup is ' + 'deprecated, use True or False instead.', + RemovedInDjango40Warning, + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params
diff --git a/tests/lookup/models.py b/tests/lookup/models.py --- a/tests/lookup/models.py +++ b/tests/lookup/models.py @@ -96,3 +96,15 @@ class Product(models.Model): class Stock(models.Model): product = models.ForeignKey(Product, models.CASCADE) qty_available = models.DecimalField(max_digits=6, decimal_places=2) + + +class Freebie(models.Model): + gift_product = models.ForeignKey(Product, models.CASCADE) + stock_id = models.IntegerField(blank=True, null=True) + + stock = models.ForeignObject( + Stock, + from_fields=['stock_id', 'gift_product'], + to_fields=['id', 'product'], + on_delete=models.CASCADE, + ) diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -9,9 +9,10 @@ from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Substr from django.test import TestCase, skipUnlessDBFeature +from django.utils.deprecation import RemovedInDjango40Warning from .models import ( - Article, Author, Game, IsNullWithNoneAsRHS, Player, Season, Tag, + Article, Author, Freebie, Game, IsNullWithNoneAsRHS, Player, Season, Tag, ) @@ -969,3 +970,24 @@ def test_exact_query_rhs_with_selected_columns(self): ).values('max_id') authors = Author.objects.filter(id=authors_max_ids[:1]) self.assertEqual(authors.get(), newest_author) + + def test_isnull_non_boolean_value(self): + # These tests will catch ValueError in Django 4.0 when using + # non-boolean values for an isnull lookup becomes forbidden. + # msg = ( + # 'The QuerySet value for an isnull lookup must be True or False.' + # ) + msg = ( + 'Using a non-boolean value for an isnull lookup is deprecated, ' + 'use True or False instead.' + ) + tests = [ + Author.objects.filter(alias__isnull=1), + Article.objects.filter(author__isnull=1), + Season.objects.filter(games__isnull=1), + Freebie.objects.filter(stock__isnull=1), + ] + for qs in tests: + with self.subTest(qs=qs): + with self.assertWarnsMessage(RemovedInDjango40Warning, msg): + qs.exists()
Prevent using __isnull lookup with non-boolean value. Description (last modified by Mariusz Felisiak) __isnull should not allow for non-boolean values. Using truthy/falsey doesn't promote INNER JOIN to an OUTER JOIN but works fine for a simple queries. Using non-boolean values is ​undocumented and untested. IMO we should raise an error for non-boolean values to avoid confusion and for consistency.
PR here: ​https://github.com/django/django/pull/11873 After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). Replying to felixxm: After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). I understand your point. But is there anything we can do to avoid people falling for the same pitfall I did? The problem, in my opinion, is that it works fine for simple queries but as soon as you add a join that needs promotion it will break, silently. Maybe we should make it raise an exception when a non-boolean is passed? One valid example is to have a class that implements __bool__. You can see here ​https://github.com/django/django/blob/d9881a025c15d87b2a7883ee50771117450ea90d/django/db/models/lookups.py#L465-L470 that non-bool value is converted to IS NULL and IS NOT NULL already using the truthy/falsy values. IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples fieldisnull='false' or fieldisnull='true' (both would return the same result). This is already the case. It just is inconsistent, in lookups.py field__isnull='false' will be a positive condition but on the query.py it will be the negative condition. Maybe adding a note on the documentation? something like: "Although it might seem like it will work with non-bool fields, this is not supported and can lead to inconsistent behaviours" Agreed, we should raise an error for non-boolean values, e.g. diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 9344979c56..fc4a38c4fe 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -463,6 +463,11 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + raise ValueError( + 'The QuerySet value for an isnull lookup must be True or ' + 'False.' + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params I changed the ticket description. Thanks, I'll work on it! Wouldn't that possibly break backward compatibility? I'm not familiar with how Django moves in that regard. We can add a release note in "Backwards incompatible changes" or deprecate this and remove in Django 4.0. I have to thing about it, please give me a day, maybe I will change my mind :) No problem. Thanks for taking the time to look into this! Another interesting example related to this: As an anecdote, I've also got bitten by this possibility. An attempt to write WHERE (field IS NULL) = boolean_field as .filter(field__isnull=F('boolean_field')) didn't go as I expected. Alexandr Aktsipetrov -- ​https://groups.google.com/forum/#!msg/django-developers/AhY2b3rxkfA/0sz3hNanCgAJ This example will generate the WHERE .... IS NULL. I guess we also would want an exception thrown here. André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Replying to felixxm: André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Sound like a good plan. Not super familiar with the branch structure of Django. So, I guess the path to follow is to make a PR to master adding the deprecation warning and eventually when master is 4.x we create the PR raising the ValueError. Is that right? Thanks! André, yes mostly. You can find more details about that ​from the documentation.
2019-10-11T18:19:39Z
3.1
["test_isnull_non_boolean_value (lookup.tests.LookupTests)", "test_iterator (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_query_rhs_with_selected_columns (lookup.tests.LookupTests)", "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_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-15320
Easy Just need to identift SUbquery class as the main issue
0
django/db/models/expressions.py
django/django
b55ebe32417e0884b6b8b3e1bc0379033aa221af
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -1149,7 +1149,8 @@ class Subquery(BaseExpression, Combinable): def __init__(self, queryset, output_field=None, **extra): # Allow the usage of both QuerySet and sql.Query objects. - self.query = getattr(queryset, 'query', queryset) + self.query = getattr(queryset, 'query', queryset).clone() + self.query.subquery = True self.extra = extra super().__init__(output_field)
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -537,6 +537,15 @@ def test_subquery_eq(self): qs.query.annotations['small_company'], ) + def test_subquery_sql(self): + employees = Employee.objects.all() + employees_subquery = Subquery(employees) + self.assertIs(employees_subquery.query.subquery, True) + self.assertIs(employees.query.subquery, False) + compiler = employees_subquery.query.get_compiler(connection=connection) + sql, _ = employees_subquery.as_sql(compiler, connection) + self.assertIn('(SELECT ', sql) + def test_in_subquery(self): # This is a contrived test (and you really wouldn't write this query), # but it is a succinct way to test the __in=Subquery() construct.
Subquery.as_sql() generates invalid SQL. Description (last modified by M1ha Shvn) Since ​this commit Subquery.as_sql(...) method returns incorrect SQL removing first and last symbols instead of absent breakets. Adding Subquery().query.subquery = True attribute fixes the problem. From my point of view, it should be set in Subquery constructor. from django.db import connection from apps.models import App q = Subquery(App.objects.all()) print(str(q.query)) # Output SQL is valid: # 'SELECT "apps_app"."id", "apps_app"."name" FROM "apps_app"' print(q.as_sql(q.query.get_compiler('default'), connection)) # Outptut SQL is invalid (no S letter at the beggining and " symbol at the end): # ('(ELECT "apps_app"."id", "apps_app"."name" FROM "apps_app)', ()) q.query.subquery = True print(q.as_sql(q.query.get_compiler('default'), connection)) # Outputs correct result ('(SELECT "apps_app"."id", "apps_app"."name" FROM "apps_app")', ())
Sounds reasonable. Sounds reasonable to me as well, I'd only suggest we .clone() the query before altering though.
2022-01-14T23:43:34Z
4.1
["test_subquery_sql (expressions.tests.BasicExpressionsTests)"]
["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_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_equal (expressions.tests.OrderByTests)", "test_hash (expressions.tests.OrderByTests)", "test_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_non_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_equal (expressions.tests.SimpleExpressionTests)", "test_hash (expressions.tests.SimpleExpressionTests)", "test_resolve_output_field (expressions.tests.CombinedExpressionTests)", "test_F_reuse (expressions.tests.ExpressionsTests)", "Special characters (e.g. %, _ and \\) stored in database are", "test_optimizations (expressions.tests.ExistsTests)", "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.", "test_decimal_expression (expressions.tests.ExpressionsNumericTests)", "We can fill a value in all objects with an other value of the", "test_filter_decimal_expression (expressions.tests.ExpressionsNumericTests)", "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_output_field_decimalfield (expressions.tests.ValueTests)", "The output field for a given Value doesn't get cleaned & validated,", "test_raise_empty_expressionlist (expressions.tests.ValueTests)", "test_repr (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)", "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_bitwise_xor_right_null (expressions.tests.ExpressionOperatorTests)", "test_lefthand_division (expressions.tests.ExpressionOperatorTests)", "test_lefthand_modulo (expressions.tests.ExpressionOperatorTests)", "test_lefthand_modulo_null (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_durationfield_multiply_divide (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_boolean_expression_combined (expressions.tests.BasicExpressionsTests)", "test_boolean_expression_combined_with_empty_Q (expressions.tests.BasicExpressionsTests)", "test_boolean_expression_in_Q (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)"]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django__django-13230
need to identify root cause as syndication.views
0
django/contrib/syndication/views.py
django/django
184a6eebb0ef56d5f1b1315a8e666830e37f3f81
diff --git a/django/contrib/syndication/views.py b/django/contrib/syndication/views.py --- a/django/contrib/syndication/views.py +++ b/django/contrib/syndication/views.py @@ -212,6 +212,7 @@ def get_feed(self, obj, request): author_name=author_name, author_email=author_email, author_link=author_link, + comments=self._get_dynamic_attr('item_comments', item), categories=self._get_dynamic_attr('item_categories', item), item_copyright=self._get_dynamic_attr('item_copyright', item), **self.item_extra_kwargs(item)
diff --git a/tests/syndication_tests/feeds.py b/tests/syndication_tests/feeds.py --- a/tests/syndication_tests/feeds.py +++ b/tests/syndication_tests/feeds.py @@ -29,6 +29,9 @@ def item_pubdate(self, item): def item_updateddate(self, item): return item.updated + def item_comments(self, item): + return "%scomments" % item.get_absolute_url() + item_author_name = 'Sally Smith' item_author_email = 'test@example.com' item_author_link = 'http://www.example.com/' diff --git a/tests/syndication_tests/tests.py b/tests/syndication_tests/tests.py --- a/tests/syndication_tests/tests.py +++ b/tests/syndication_tests/tests.py @@ -136,10 +136,20 @@ def test_rss2_feed(self): 'guid': 'http://example.com/blog/1/', 'pubDate': pub_date, 'author': 'test@example.com (Sally Smith)', + 'comments': '/blog/1/comments', }) self.assertCategories(items[0], ['python', 'testing']) for item in items: - self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'category', 'pubDate', 'author']) + self.assertChildNodes(item, [ + 'title', + 'link', + 'description', + 'guid', + 'category', + 'pubDate', + 'author', + 'comments', + ]) # Assert that <guid> does not have any 'isPermaLink' attribute self.assertIsNone(item.getElementsByTagName( 'guid')[0].attributes.get('isPermaLink'))
Add support for item_comments to syndication framework Description Add comments argument to feed.add_item() in syndication.views so that item_comments can be defined directly without having to take the detour via item_extra_kwargs . Additionally, comments is already explicitly mentioned in the feedparser, but not implemented in the view.
2020-07-23T14:59:50Z
3.2
["test_rss2_feed (syndication_tests.tests.SyndicationFeedTest)"]
["test_add_domain (syndication_tests.tests.SyndicationFeedTest)", "test_atom_feed (syndication_tests.tests.SyndicationFeedTest)", "test_atom_feed_published_and_updated_elements (syndication_tests.tests.SyndicationFeedTest)", "test_atom_multiple_enclosures (syndication_tests.tests.SyndicationFeedTest)", "test_atom_single_enclosure (syndication_tests.tests.SyndicationFeedTest)", "test_aware_datetime_conversion (syndication_tests.tests.SyndicationFeedTest)", "test_custom_feed_generator (syndication_tests.tests.SyndicationFeedTest)", "test_feed_generator_language_attribute (syndication_tests.tests.SyndicationFeedTest)", "test_feed_last_modified_time (syndication_tests.tests.SyndicationFeedTest)", "test_feed_last_modified_time_naive_date (syndication_tests.tests.SyndicationFeedTest)", "test_feed_url (syndication_tests.tests.SyndicationFeedTest)", "test_item_link_error (syndication_tests.tests.SyndicationFeedTest)", "test_latest_post_date (syndication_tests.tests.SyndicationFeedTest)", "test_naive_datetime_conversion (syndication_tests.tests.SyndicationFeedTest)", "test_rss091_feed (syndication_tests.tests.SyndicationFeedTest)", "test_rss2_feed_guid_permalink_false (syndication_tests.tests.SyndicationFeedTest)", "test_rss2_feed_guid_permalink_true (syndication_tests.tests.SyndicationFeedTest)", "test_rss2_multiple_enclosures (syndication_tests.tests.SyndicationFeedTest)", "test_rss2_single_enclosure (syndication_tests.tests.SyndicationFeedTest)", "test_secure_urls (syndication_tests.tests.SyndicationFeedTest)", "test_template_context_feed (syndication_tests.tests.SyndicationFeedTest)", "test_template_feed (syndication_tests.tests.SyndicationFeedTest)", "test_title_escaping (syndication_tests.tests.SyndicationFeedTest)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django__django-11179
root cause file
0
django/db/models/deletion.py
django/django
19fc6376ce67d01ca37a91ef2f55ef769f50513a
diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py --- a/django/db/models/deletion.py +++ b/django/db/models/deletion.py @@ -277,6 +277,7 @@ def delete(self): if self.can_fast_delete(instance): with transaction.mark_for_rollback_on_error(): count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using) + setattr(instance, model._meta.pk.attname, None) return count, {model._meta.label: count} with transaction.atomic(using=self.using, savepoint=False):
diff --git a/tests/delete/tests.py b/tests/delete/tests.py --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -1,6 +1,7 @@ from math import ceil from django.db import IntegrityError, connection, models +from django.db.models.deletion import Collector from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature @@ -471,6 +472,14 @@ def test_fast_delete_qs(self): self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.filter(pk=u2.pk).exists()) + def test_fast_delete_instance_set_pk_none(self): + u = User.objects.create() + # User can be fast-deleted. + collector = Collector(using='default') + self.assertTrue(collector.can_fast_delete(u)) + u.delete() + self.assertIsNone(u.pk) + def test_fast_delete_joined_qs(self): a = Avatar.objects.create(desc='a') User.objects.create(avatar=a)
delete() on instances of models without any dependencies doesn't clear PKs. Description Deleting any model with no dependencies not updates the PK on the model. It should be set to None after .delete() call. See Django.db.models.deletion:276-281. Should update the model line 280.
Reproduced at 1ffddfc233e2d5139cc6ec31a4ec6ef70b10f87f. Regression in bc7dd8490b882b2cefdc7faf431dc64c532b79c9. Thanks for the report. Regression test. I have attached a simple fix which mimics what ​https://github.com/django/django/blob/master/django/db/models/deletion.py#L324-L326 does for multiple objects. I am not sure if we need ​https://github.com/django/django/blob/master/django/db/models/deletion.py#L320-L323 (the block above) because I think field_updates is only ever filled if the objects are not fast-deletable -- ie ​https://github.com/django/django/blob/master/django/db/models/deletion.py#L224 is not called due to the can_fast_delete check at the beginning of the collect function. That said, if we want to be extra "safe" we can just move lines 320 - 326 into an extra function and call that from the old and new location (though I do not think it is needed).
2019-04-05T15:54:39Z
3.0
["test_fast_delete_instance_set_pk_none (delete.tests.FastDeleteTests)"]
["test_fast_delete_empty_no_update_can_self_select (delete.tests.FastDeleteTests)", "test_fast_delete_fk (delete.tests.FastDeleteTests)", "test_fast_delete_inheritance (delete.tests.FastDeleteTests)", "test_fast_delete_joined_qs (delete.tests.FastDeleteTests)", "test_fast_delete_large_batch (delete.tests.FastDeleteTests)", "test_fast_delete_m2m (delete.tests.FastDeleteTests)", "test_fast_delete_qs (delete.tests.FastDeleteTests)", "test_fast_delete_revm2m (delete.tests.FastDeleteTests)", "test_auto (delete.tests.OnDeleteTests)", "test_auto_nullable (delete.tests.OnDeleteTests)", "test_cascade (delete.tests.OnDeleteTests)", "test_cascade_from_child (delete.tests.OnDeleteTests)", "test_cascade_from_parent (delete.tests.OnDeleteTests)", "test_cascade_nullable (delete.tests.OnDeleteTests)", "test_do_nothing (delete.tests.OnDeleteTests)", "test_do_nothing_qscount (delete.tests.OnDeleteTests)", "test_inheritance_cascade_down (delete.tests.OnDeleteTests)", "test_inheritance_cascade_up (delete.tests.OnDeleteTests)", "test_o2o_setnull (delete.tests.OnDeleteTests)", "test_protect (delete.tests.OnDeleteTests)", "test_setdefault (delete.tests.OnDeleteTests)", "test_setdefault_none (delete.tests.OnDeleteTests)", "test_setnull (delete.tests.OnDeleteTests)", "test_setnull_from_child (delete.tests.OnDeleteTests)", "test_setnull_from_parent (delete.tests.OnDeleteTests)", "test_setvalue (delete.tests.OnDeleteTests)", "test_bulk (delete.tests.DeletionTests)", "test_can_defer_constraint_checks (delete.tests.DeletionTests)", "test_delete_with_keeping_parents (delete.tests.DeletionTests)", "test_delete_with_keeping_parents_relationships (delete.tests.DeletionTests)", "test_deletion_order (delete.tests.DeletionTests)", "test_hidden_related (delete.tests.DeletionTests)", "test_instance_update (delete.tests.DeletionTests)", "test_large_delete (delete.tests.DeletionTests)", "test_large_delete_related (delete.tests.DeletionTests)", "test_m2m (delete.tests.DeletionTests)", "test_model_delete_returns_num_rows (delete.tests.DeletionTests)", "test_proxied_model_duplicate_queries (delete.tests.DeletionTests)", "test_queryset_delete_returns_num_rows (delete.tests.DeletionTests)", "test_relational_post_delete_signals_happen_before_parent_object (delete.tests.DeletionTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django__django-15781
cant understand even for a human
1
django/core/management/base.py
django/django
8d160f154f0240a423e83ffe0690e472f837373c
diff --git a/django/core/management/base.py b/django/core/management/base.py --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -286,10 +286,10 @@ def create_parser(self, prog_name, subcommand, **kwargs): Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ + kwargs.setdefault("formatter_class", DjangoHelpFormatter) parser = CommandParser( prog="%s %s" % (os.path.basename(prog_name), subcommand), description=self.help or None, - formatter_class=DjangoHelpFormatter, missing_args_message=getattr(self, "missing_args_message", None), called_from_command_line=getattr(self, "_called_from_command_line", None), **kwargs,
diff --git a/tests/user_commands/tests.py b/tests/user_commands/tests.py --- a/tests/user_commands/tests.py +++ b/tests/user_commands/tests.py @@ -1,4 +1,5 @@ import os +from argparse import ArgumentDefaultsHelpFormatter from io import StringIO from unittest import mock @@ -408,8 +409,14 @@ def test_subparser_invalid_option(self): def test_create_parser_kwargs(self): """BaseCommand.create_parser() passes kwargs to CommandParser.""" epilog = "some epilog text" - parser = BaseCommand().create_parser("prog_name", "subcommand", epilog=epilog) + parser = BaseCommand().create_parser( + "prog_name", + "subcommand", + epilog=epilog, + formatter_class=ArgumentDefaultsHelpFormatter, + ) self.assertEqual(parser.epilog, epilog) + self.assertEqual(parser.formatter_class, ArgumentDefaultsHelpFormatter) def test_outputwrapper_flush(self): out = StringIO()
Customizable management command formatters. Description With code like: class Command(BaseCommand): help = ''' Import a contract from tzkt. Example usage: ./manage.py tzkt_import 'Tezos Mainnet' KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe ''' Help output is: $ ./manage.py help tzkt_import usage: manage.py tzkt_import [-h] [--api API] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] blockchain target Import a contract from tzkt Example usage: ./manage.py tzkt_import 'Tezos Mainnet' KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe positional arguments: blockchain Name of the blockchain to import into target Id of the contract to import When that was expected: $ ./manage.py help tzkt_import usage: manage.py tzkt_import [-h] [--api API] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] blockchain target Import a contract from tzkt Example usage: ./manage.py tzkt_import 'Tezos Mainnet' KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe positional arguments: blockchain Name of the blockchain to import into target Id of the contract to import
This seems no fault of Django but is rather ​the default behavior of ArgumentParser ("By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages"). This can be changed by using a custom ​formatter_class, though Django already specifies a custom one (​DjangoHelpFormatter). It seems reasonable, to make it customizable by passing via kwargs to the ​BaseCommand.create_parser() (as documented): django/core/management/base.py diff --git a/django/core/management/base.py b/django/core/management/base.py index f0e711ac76..52407807d8 100644 a b class BaseCommand: 286286 Create and return the ``ArgumentParser`` which will be used to 287287 parse the arguments to this command. 288288 """ 289 kwargs.setdefault("formatter_class", DjangoHelpFormatter) 289290 parser = CommandParser( 290291 prog="%s %s" % (os.path.basename(prog_name), subcommand), 291292 description=self.help or None, 292 formatter_class=DjangoHelpFormatter, 293293 missing_args_message=getattr(self, "missing_args_message", None), 294294 called_from_command_line=getattr(self, "_called_from_command_line", None), 295295 **kwargs, What do you think? Looks good but I don't see a reason for keeping a default that swallows newlines because PEP257 forbids having a multiline sentence on the first line anyway: Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. As such, the default formater which purpose is to unwrap the first sentence encourages breaking PEP 257. And users who are naturally complying with PEP257 will have to override the formatter, it should be the other way around. Also, the not-unwraping formater will also look fine with existing docstrings, it will work for both use cases, while the current one only works for one use case and breaks the other. The default formater should work for both Replying to James Pic: Also, the not-unwraping formater will also look fine with existing docstrings, it will work for both use cases, while the current one only works for one use case and breaks the other. The default formater should work for both It seems you think that Python's (not Django's) default behavior should be changed according to PEP 257. I'd recommend to start a discussion in Python's bugtracker. As far as I'm aware the proposed solution will allow users to freely change a formatter, which should be enough from the Django point of view. No, I think that Django's default behavior should match Python's PEP 257, and at the same time, have a default that works in all use cases. I think my report and comments are pretty clear, I fail to understand how you could get my comment completely backward, so, unless you have any specific question about this statement, I'm going to give up on this. So as part of this issue, do we make changes to allow a user to override the formatter through kwargs and also keep DjangoHelpFormatter as the default? Replying to Subhankar Hotta: So as part of this issue, do we make changes to allow a user to override the formatter through kwargs and also keep DjangoHelpFormatter as the default? Yes, see comment.
2022-06-18T19:39:34Z
4.2
["BaseCommand.create_parser() passes kwargs to CommandParser."]
["test_get_random_secret_key (user_commands.tests.UtilsTests)", "test_is_ignored_path_false (user_commands.tests.UtilsTests)", "test_is_ignored_path_true (user_commands.tests.UtilsTests)", "test_no_existent_external_program (user_commands.tests.UtilsTests)", "test_normalize_path_patterns_truncates_wildcard_base (user_commands.tests.UtilsTests)", "By default, call_command should not trigger the check framework, unless", "When passing the long option name to call_command, the available option", "It should be possible to pass non-string arguments to call_command.", "test_call_command_unrecognized_option (user_commands.tests.CommandTests)", "test_call_command_with_required_parameters_in_mixed_options (user_commands.tests.CommandTests)", "test_call_command_with_required_parameters_in_options (user_commands.tests.CommandTests)", "test_calling_a_command_with_no_app_labels_and_parameters_raise_command_error (user_commands.tests.CommandTests)", "test_calling_a_command_with_only_empty_parameter_should_ends_gracefully (user_commands.tests.CommandTests)", "test_calling_command_with_app_labels_and_parameters_should_be_ok (user_commands.tests.CommandTests)", "test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok (user_commands.tests.CommandTests)", "test_check_migrations (user_commands.tests.CommandTests)", "test_command (user_commands.tests.CommandTests)", "test_command_add_arguments_after_common_arguments (user_commands.tests.CommandTests)", "test_command_style (user_commands.tests.CommandTests)", "Management commands can also be loaded from Python eggs.", "An unknown command raises CommandError", "find_command should still work when the PATH environment variable", "test_language_preserved (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_const_options (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_options (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_with_same_dest_args (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_with_same_dest_options (user_commands.tests.CommandTests)", "When the Command handle method is decorated with @no_translations,", "test_output_transaction (user_commands.tests.CommandTests)", "test_outputwrapper_flush (user_commands.tests.CommandTests)", "test_required_const_options (user_commands.tests.CommandTests)", "test_required_list_option (user_commands.tests.CommandTests)", "test_requires_system_checks_empty (user_commands.tests.CommandTests)", "test_requires_system_checks_invalid (user_commands.tests.CommandTests)", "test_requires_system_checks_specific (user_commands.tests.CommandTests)", "test_subparser (user_commands.tests.CommandTests)", "test_subparser_dest_args (user_commands.tests.CommandTests)", "test_subparser_dest_required_args (user_commands.tests.CommandTests)", "test_subparser_invalid_option (user_commands.tests.CommandTests)", "Exception raised in a command should raise CommandError with", "To avoid conflicts with custom options, commands don't allow", "test_script_prefix_set_in_commands (user_commands.tests.CommandRunTests)", "test_skip_checks (user_commands.tests.CommandRunTests)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django__django-13710
file structure name search need ti handle large code files as well
0
django/contrib/admin/options.py
django/django
1bd6a7a0acc11e249fca11c017505ad39f15ebf6
diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -2037,10 +2037,13 @@ def __init__(self, parent_model, admin_site): self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) super().__init__() + if self.verbose_name_plural is None: + if self.verbose_name is None: + self.verbose_name_plural = self.model._meta.verbose_name_plural + else: + self.verbose_name_plural = format_lazy('{}s', self.verbose_name) if self.verbose_name is None: self.verbose_name = self.model._meta.verbose_name - if self.verbose_name_plural is None: - self.verbose_name_plural = self.model._meta.verbose_name_plural @property def media(self):
diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py --- a/tests/admin_inlines/tests.py +++ b/tests/admin_inlines/tests.py @@ -967,6 +967,55 @@ def test_extra_inlines_are_not_shown(self): class TestVerboseNameInlineForms(TestDataMixin, TestCase): factory = RequestFactory() + def test_verbose_name_inline(self): + class NonVerboseProfileInline(TabularInline): + model = Profile + verbose_name = 'Non-verbose childs' + + class VerboseNameProfileInline(TabularInline): + model = VerboseNameProfile + verbose_name = 'Childs with verbose name' + + class VerboseNamePluralProfileInline(TabularInline): + model = VerboseNamePluralProfile + verbose_name = 'Childs with verbose name plural' + + class BothVerboseNameProfileInline(TabularInline): + model = BothVerboseNameProfile + verbose_name = 'Childs with both verbose names' + + modeladmin = ModelAdmin(ProfileCollection, admin_site) + modeladmin.inlines = [ + NonVerboseProfileInline, + VerboseNameProfileInline, + VerboseNamePluralProfileInline, + BothVerboseNameProfileInline, + ] + obj = ProfileCollection.objects.create() + url = reverse('admin:admin_inlines_profilecollection_change', args=(obj.pk,)) + request = self.factory.get(url) + request.user = self.superuser + response = modeladmin.changeform_view(request) + self.assertNotContains(response, 'Add another Profile') + # Non-verbose model. + self.assertContains(response, '<h2>Non-verbose childss</h2>') + self.assertContains(response, 'Add another Non-verbose child') + self.assertNotContains(response, '<h2>Profiles</h2>') + # Model with verbose name. + self.assertContains(response, '<h2>Childs with verbose names</h2>') + self.assertContains(response, 'Add another Childs with verbose name') + self.assertNotContains(response, '<h2>Model with verbose name onlys</h2>') + self.assertNotContains(response, 'Add another Model with verbose name only') + # Model with verbose name plural. + self.assertContains(response, '<h2>Childs with verbose name plurals</h2>') + self.assertContains(response, 'Add another Childs with verbose name plural') + self.assertNotContains(response, '<h2>Model with verbose name plural only</h2>') + # Model with both verbose names. + self.assertContains(response, '<h2>Childs with both verbose namess</h2>') + self.assertContains(response, 'Add another Childs with both verbose names') + self.assertNotContains(response, '<h2>Model with both - plural name</h2>') + self.assertNotContains(response, 'Add another Model with both - name') + def test_verbose_name_plural_inline(self): class NonVerboseProfileInline(TabularInline): model = Profile
Use Admin Inline verbose_name as default for Inline verbose_name_plural Description Django allows specification of a verbose_name and a verbose_name_plural for Inline classes in admin views. However, verbose_name_plural for an Inline is not currently based on a specified verbose_name. Instead, it continues to be based on the model name, or an a verbose_name specified in the model's Meta class. This was confusing to me initially (I didn't understand why I had to specify both name forms for an Inline if I wanted to overrule the default name), and seems inconsistent with the approach for a model's Meta class (which does automatically base the plural form on a specified verbose_name). I propose that verbose_name_plural for an Inline class should by default be based on the verbose_name for an Inline if that is specified. I have written a patch to implement this, including tests. Would be happy to submit that.
Please push your patch as a ​Django pull request.
2020-11-23T04:39:05Z
4.0
["test_verbose_name_inline (admin_inlines.tests.TestVerboseNameInlineForms)"]
["Regression for #9362", "test_deleting_inline_with_protected_delete_does_not_validate (admin_inlines.tests.TestInlineProtectedOnDelete)", "test_all_inline_media (admin_inlines.tests.TestInlineMedia)", "test_inline_media_only_base (admin_inlines.tests.TestInlineMedia)", "test_inline_media_only_inline (admin_inlines.tests.TestInlineMedia)", "test_both_verbose_names_inline (admin_inlines.tests.TestVerboseNameInlineForms)", "test_verbose_name_plural_inline (admin_inlines.tests.TestVerboseNameInlineForms)", "test_add_url_not_allowed (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_extra_inlines_are_not_shown (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_get_to_change_url_is_allowed (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_inline_delete_buttons_are_not_shown (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_inlines_are_rendered_as_read_only (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_main_model_is_rendered_as_read_only (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_post_to_change_url_not_allowed (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_submit_line_shows_only_close_button (admin_inlines.tests.TestReadOnlyChangeViewInlinePermissions)", "test_inline_add_fk_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_add_fk_noperm (admin_inlines.tests.TestInlinePermissions)", "test_inline_add_m2m_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_add_m2m_noperm (admin_inlines.tests.TestInlinePermissions)", "test_inline_add_m2m_view_only_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_add_change_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_all_perms (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_change_del_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_change_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_noperm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_m2m_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_m2m_change_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_m2m_noperm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_m2m_view_only_perm (admin_inlines.tests.TestInlinePermissions)", "Admin inline should invoke local callable when its name is listed in readonly_fields", "can_delete should be passed to inlineformset factory.", "An object can be created with inlines when it inherits another class.", "test_custom_form_tabular_inline_extra_field_label (admin_inlines.tests.TestInline)", "A model form with a form field specified (TitleForm.title1) should have", "SomeChildModelForm.__init__() overrides the label of a form field.", "test_custom_get_extra_form (admin_inlines.tests.TestInline)", "test_custom_min_num (admin_inlines.tests.TestInline)", "The \"View on Site\" link is correct for models with a custom primary key", "The inlines' model field help texts are displayed when using both the", "test_inline_editable_pk (admin_inlines.tests.TestInline)", "#18263 -- Make sure hidden fields don't get a column in tabular inlines", "test_inline_nonauto_noneditable_inherited_pk (admin_inlines.tests.TestInline)", "test_inline_nonauto_noneditable_pk (admin_inlines.tests.TestInline)", "test_inline_primary (admin_inlines.tests.TestInline)", "test_inlines_plural_heading_foreign_key (admin_inlines.tests.TestInline)", "Inlines `show_change_link` for registered models when enabled.", "Inlines `show_change_link` disabled for unregistered models.", "test_inlines_singular_heading_one_to_one (admin_inlines.tests.TestInline)", "The \"View on Site\" link is correct for locales that use thousand", "Autogenerated many-to-many inlines are displayed correctly (#13407)", "min_num and extra determine number of forms.", "Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable", "test_non_editable_custom_form_tabular_inline_extra_field_label (admin_inlines.tests.TestInline)", "Multiple inlines with related_name='+' have correct form prefixes.", "Inlines without change permission shows field inputs on add form.", "Bug #13174.", "test_stacked_inline_edit_form_contains_has_original_class (admin_inlines.tests.TestInline)", "Field names are included in the context to output a field-specific", "Inlines `show_change_link` disabled by default.", "Tabular inlines use ModelForm.Meta.help_texts and labels for read-only", "non_field_errors are displayed correctly, including the correct value"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-10924
need to identify issue is wirh FilePathField and level iszero
0
django/db/models/fields/__init__.py
django/django
bceadd2788dc2dad53eba0caae172bd8522fd483
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -1709,7 +1709,7 @@ def get_prep_value(self, value): def formfield(self, **kwargs): return super().formfield(**{ - 'path': self.path, + 'path': self.path() if callable(self.path) else self.path, 'match': self.match, 'recursive': self.recursive, 'form_class': forms.FilePathField,
diff --git a/tests/model_fields/test_filepathfield.py b/tests/model_fields/test_filepathfield.py new file mode 100644 --- /dev/null +++ b/tests/model_fields/test_filepathfield.py @@ -0,0 +1,22 @@ +import os + +from django.db.models import FilePathField +from django.test import SimpleTestCase + + +class FilePathFieldTests(SimpleTestCase): + def test_path(self): + path = os.path.dirname(__file__) + field = FilePathField(path=path) + self.assertEqual(field.path, path) + self.assertEqual(field.formfield().path, path) + + def test_callable_path(self): + path = os.path.dirname(__file__) + + def generate_path(): + return path + + field = FilePathField(path=generate_path) + self.assertEqual(field.path(), path) + self.assertEqual(field.formfield().path, path)
Allow FilePathField path to accept a callable. Description I have a special case where I want to create a model containing the path to some local files on the server/dev machine. Seeing as the place where these files are stored is different on different machines I have the following: import os from django.conf import settings from django.db import models class LocalFiles(models.Model): name = models.CharField(max_length=255) file = models.FilePathField(path=os.path.join(settings.LOCAL_FILE_DIR, 'example_dir')) Now when running manage.py makemigrations it will resolve the path based on the machine it is being run on. Eg: /home/<username>/server_files/example_dir I had to manually change the migration to include the os.path.join() part to not break this when running the migration on production/other machine.
So, to clarify, what exactly is the bug/feature proposal/issue here? The way I see it, you're supposed to use os.path.join() and LOCAL_FILE_DIR to define a relative path. It's sort of like how we use BASE_DIR to define relative paths in a lot of other places. Could you please clarify a bit more as to what the issue is so as to make it easier to test and patch? Replying to Hemanth V. Alluri: So, to clarify, what exactly is the bug/feature proposal/issue here? The way I see it, you're supposed to use os.path.join() and LOCAL_FILE_DIR to define a relative path. It's sort of like how we use BASE_DIR to define relative paths in a lot of other places. Could you please clarify a bit more as to what the issue is so as to make it easier to test and patch? LOCAL_FILE_DIR doesn't have to be the same on another machine, and in this case it isn't the same on the production server. So the os.path.join() will generate a different path on my local machine compared to the server. When i ran ./manage.py makemigrations the Migration had the path resolved "hardcoded" to my local path, which will not work when applying that path on the production server. This will also happen when using the BASE_DIR setting as the path of your FilePathField, seeing as that's based on the location of your project folder, which will almost always be on a different location. My suggestion would be to let makemigrations not resolve the path and instead keep the os.path.join(), which I have now done manually. More importantly would be to retain the LOCAL_FILE_DIR setting in the migration. Replying to Sebastiaan Arendsen: Replying to Hemanth V. Alluri: So, to clarify, what exactly is the bug/feature proposal/issue here? The way I see it, you're supposed to use os.path.join() and LOCAL_FILE_DIR to define a relative path. It's sort of like how we use BASE_DIR to define relative paths in a lot of other places. Could you please clarify a bit more as to what the issue is so as to make it easier to test and patch? LOCAL_FILE_DIR doesn't have to be the same on another machine, and in this case it isn't the same on the production server. So the os.path.join() will generate a different path on my local machine compared to the server. When i ran ./manage.py makemigrations the Migration had the path resolved "hardcoded" to my local path, which will not work when applying that path on the production server. This will also happen when using the BASE_DIR setting as the path of your FilePathField, seeing as that's based on the location of your project folder, which will almost always be on a different location. My suggestion would be to let makemigrations not resolve the path and instead keep the os.path.join(), which I have now done manually. More importantly would be to retain the LOCAL_FILE_DIR setting in the migration. Please look at this ticket: https://code.djangoproject.com/ticket/6896 I think that something like what sandychapman suggested about an extra flag would be cool if the design decision was approved and if there were no restrictions in the implementation for such a change to be made. But that's up to the developers who have had more experience with the project to decide, not me. This seems a reasonable use-case: allow FilePathField to vary path by environment. The trouble with os.path.join(...) is that it will always be interpreted at import time, when the class definition is loaded. (The (...) say, ...and call this....) The way to defer that would be to all path to accept a callable, similarly to how FileField's upload_to takes a callable. It should be enough to evaluate the callable in FilePathField.__init__(). Experimenting with generating a migration looks good. (The operation gives path the fully qualified import path of the specified callable, just as with upload_to.) I'm going to tentatively mark this as Easy Pickings: it should be simple enough. Replying to Nicolas Noé: Hi Nicolas, Are you still working on this ticket? Sorry, I forgot about it. I'll try to solve this real soon (or release the ticket if I can't find time for it). ​PR Can I work on this ticket ? Sure, sorry for blocking the ticket while I was too busy... I think that Nicolas Noe's solution, ​PR, was correct. The model field can accept a callable as it is currently implemented. If you pass it a callable for the path argument it will correctly use that fully qualified function import path in the migration. The problem is when you go to actually instantiate a FilePathField instance, the FilePathField form does some type checking and gives you one of these TypeError: scandir: path should be string, bytes, os.PathLike or None, not function This can be avoided by evaluating the path function first thing in the field form __init__ function, as in the pull request. Then everything seems to work fine. Hi, If I only change self.path in forms/fields.py, right after __init__ I get this error: File "/home/hpfn/Documentos/Programacao/python/testes/.venv/lib/python3.6/site-packages/django/forms/fields.py", line 1106, in __init__ self.choices.append((f, f.replace(path, "", 1))) TypeError: replace() argument 1 must be str, not function The 'path' param is used a few lines after. There is one more time. Line 1106 can be wrong. If I put in models/fields/__init__.py - after super(): if callable(self.path): self.path = self.path() I can run 'python manage.py runserver' It can be: if callable(path): path = path() at the beginning of forms/fields.py ​PR All comments in the original PR (​https://github.com/django/django/pull/10299/commits/7ddb83ca7ed5b2a586e9d4c9e0a79d60b27c26b6) seems to be resolved in the latter one (​https://github.com/django/django/pull/10924/commits/9c3b2c85e46efcf1c916e4b76045d834f16050e3). Any hope of this featuring coming through. Django keep bouncing between migrations due to different paths to models.FilePathField
2019-02-03T11:30:12Z
3.0
["test_callable_path (model_fields.test_filepathfield.FilePathFieldTests)"]
["test_path (model_fields.test_filepathfield.FilePathFieldTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django__django-13315
need a trie
0
django/forms/models.py
django/django
36bc47069ce071e80c8129500de3b8664d2058a7
diff --git a/django/forms/models.py b/django/forms/models.py --- a/django/forms/models.py +++ b/django/forms/models.py @@ -97,10 +97,18 @@ def model_to_dict(instance, fields=None, exclude=None): def apply_limit_choices_to_to_formfield(formfield): """Apply limit_choices_to to the formfield's queryset if needed.""" + from django.db.models import Exists, OuterRef, Q if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'): limit_choices_to = formfield.get_limit_choices_to() - if limit_choices_to is not None: - formfield.queryset = formfield.queryset.complex_filter(limit_choices_to) + if limit_choices_to: + complex_filter = limit_choices_to + if not isinstance(complex_filter, Q): + complex_filter = Q(**limit_choices_to) + complex_filter &= Q(pk=OuterRef('pk')) + # Use Exists() to avoid potential duplicates. + formfield.queryset = formfield.queryset.filter( + Exists(formfield.queryset.model._base_manager.filter(complex_filter)), + ) def fields_for_model(model, fields=None, exclude=None, widgets=None,
diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py --- a/tests/model_forms/models.py +++ b/tests/model_forms/models.py @@ -411,9 +411,14 @@ class StumpJoke(models.Model): Character, models.CASCADE, limit_choices_to=today_callable_dict, - related_name="+", + related_name='jokes', ) - has_fooled_today = models.ManyToManyField(Character, limit_choices_to=today_callable_q, related_name="+") + has_fooled_today = models.ManyToManyField( + Character, + limit_choices_to=today_callable_q, + related_name='jokes_today', + ) + funny = models.BooleanField(default=False) # Model for #13776 diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -16,6 +16,7 @@ ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature +from django.test.utils import isolate_apps from .models import ( Article, ArticleStatus, Author, Author1, Award, BetterWriter, BigInt, Book, @@ -2829,6 +2830,72 @@ def test_callable_called_each_time_form_is_instantiated(self): StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 3) + @isolate_apps('model_forms') + def test_limit_choices_to_no_duplicates(self): + joke1 = StumpJoke.objects.create( + funny=True, + most_recently_fooled=self.threepwood, + ) + joke2 = StumpJoke.objects.create( + funny=True, + most_recently_fooled=self.threepwood, + ) + joke3 = StumpJoke.objects.create( + funny=True, + most_recently_fooled=self.marley, + ) + StumpJoke.objects.create(funny=False, most_recently_fooled=self.marley) + joke1.has_fooled_today.add(self.marley, self.threepwood) + joke2.has_fooled_today.add(self.marley) + joke3.has_fooled_today.add(self.marley, self.threepwood) + + class CharacterDetails(models.Model): + character1 = models.ForeignKey( + Character, + models.CASCADE, + limit_choices_to=models.Q( + jokes__funny=True, + jokes_today__funny=True, + ), + related_name='details_fk_1', + ) + character2 = models.ForeignKey( + Character, + models.CASCADE, + limit_choices_to={ + 'jokes__funny': True, + 'jokes_today__funny': True, + }, + related_name='details_fk_2', + ) + character3 = models.ManyToManyField( + Character, + limit_choices_to=models.Q( + jokes__funny=True, + jokes_today__funny=True, + ), + related_name='details_m2m_1', + ) + + class CharacterDetailsForm(forms.ModelForm): + class Meta: + model = CharacterDetails + fields = '__all__' + + form = CharacterDetailsForm() + self.assertCountEqual( + form.fields['character1'].queryset, + [self.marley, self.threepwood], + ) + self.assertCountEqual( + form.fields['character2'].queryset, + [self.marley, self.threepwood], + ) + self.assertCountEqual( + form.fields['character3'].queryset, + [self.marley, self.threepwood], + ) + class FormFieldCallbackTests(SimpleTestCase):
limit_choices_to on a ForeignKey can render duplicate options in formfield Description If you pass a Q object as limit_choices_to on a ForeignKey field involving a join, you may end up with duplicate options in your form. See regressiontest in patch for a clear view on the problem.
Replying to SmileyChris: I've updated the patch to resolve the conflicts I've had since you flagged this one as "Ready for checkin". No real change. update resolving conflict Is there something I can do to get this checked in? I re-read the ​Triage docs. As far as I can see "A developer checks in the fix" is the only step left. The ​1.2 roadmap shows that we're in a feature freeze. I'd suggest bringing this up on the django-dev google group a week or so after 1.2 final is released. In [15607]: Fixed #11707 - limit_choices_to on a ForeignKey can render duplicate options in formfield Thanks to Chris Wesseling for the report and patch. In [15610]: [1.2.X] Fixed #11707 - limit_choices_to on a ForeignKey can render duplicate options in formfield Thanks to Chris Wesseling for the report and patch. Backport of [15607] from trunk. In [15791]: Fixed #15559 - distinct queries introduced by [15607] cause errors with some custom model fields This patch just reverts [15607] until a more satisfying solution can be found. Refs #11707 In [15792]: [1.2.X] Fixed #15559 - distinct queries introduced by [15607] cause errors with some custom model fields This patch just reverts [15607] until a more satisfying solution can be found. Refs #11707 Backport of [15791] from trunk. Re-opened due to the fix being reverted, as above. For future reference, a possible alternative solution might be to do filtering of duplicates in Python, at the point of rendering the form field, rather than in the database. Replying to lukeplant: (The changeset message doesn't reference this ticket) Can someone point me to an example of such a custom model field or, even better, a test showing the breakage? Replying to lukeplant: For future reference, a possible alternative solution might be to do filtering of duplicates in Python, at the point of rendering the form field, rather than in the database. Assuming 'limit_choices_to' is only used by Forms... Replying to charstring: Replying to lukeplant: (The changeset message doesn't reference this ticket) Can someone point me to an example of such a custom model field or, even better, a test showing the breakage? The discussion linked from the description of the other ticket has an example. It's in dpaste so may not be long-lived. Copying here for reference: class PointField(models.Field): description = _("A geometric point") __metaclass__ = models.SubfieldBase pattern = re.compile('^\(([\d\.]+),([\d\.]+)\)$') def db_type(self, connection): if connection.settings_dict['ENGINE'] is not 'django.db.backends.postgresql_psycopg2': return None return 'point' def to_python(self, value): if isinstance(value, tuple): return (float(value[0]), float(value[1])) if not value: return (0, 0) match = self.pattern.findall(value)[0] return (float(match[0]), float(match[1])) def get_prep_value(self, value): return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return '({0}, {1})'.format(value[0], value[1]) def get_prep_lookup(self, lookup_type, value): raise TypeError('Lookup type %r not supported.' % lookup_type) def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_db_prep_value(value) This is nasty because it not only renders duplicates but also blows up when .get() is called on the queryset if you select one of the duplicates (MultipleObjectsReturned). Talked to Russ. Picked one of the unclean solutions: filter in python before displaying and checking again before getting the choice. Thanks to Jonas and Roald! just removed a the previous fix from the comments This issue also breaks ModelChoiceField - MultipleObjectsReturned error Replying to simon29: This issue also breaks ModelChoiceField - MultipleObjectsReturned error By "this issue also breaks", do you mean, you've tried the patch and it needs improvement? If it does work, please set it to "ready for checkin". backported to 1.2.X and refactored to reduce complexity Refactored less complex against trunk against 1.3.X branch Discussion from IRC: [02:24am] I don't see a test case here that emulates the failures seen when the previous (committed then reverted) approach. Am I just missing it? [09:26am] jacobkm: I also can't say I'm particularly happy with the patch, particularly iterating over the qs in distinct_choices(). [09:26am] chars:It's pretty hard to test for me. It's a case where Postgres can't compare the values. [09:26am] chars: So it can't test for uniqueness [09:26am] jacobkm: It also needs additions to documentation to mention that Q() objects are acceptable in limit_choices_to. Replying to jacob: Discussion from IRC: [09:26am] jacobkm: It also needs additions to documentation to mention that Q() objects are acceptable in limit_choices_to. ​Documentation on ForeignKey.limit_choices_to already mentions: "Instead of a dictionary this can also be a Q object for more complex queries." Further discussion: 17:00 < chars> jacobkm: The only known case that broke the original .distinct() solution was in Postgres. So maybe if #6422 gets accepted, we could test for the distinct_on_fields feature and then distinct on the pk, which is unique by definition. 17:00 < jacobkm> chars: see now *that* makes me a lot happier. 17:00 < chars> And fallback to the vanilla .distinct() if the backend doesn't support it. That's #6422. DISTINCT is just a special GROUP BY... So an empty .annotate() does the trick too, since it groups by the pk. And the DBMS should by definition be able to compare pk's. I'll try to put up a patch tonight. Replying to charstring: DISTINCT is just a special GROUP BY... So an empty .annotate() does the trick too, since it groups by the pk. And the DBMS should by definition be able to compare pk's. I'll try to put up a patch tonight. Well, that was a long night. ;) I got implemented the .annotate() solution in here ​https://github.com/CharString/django/tree/ticket-11707 Is the PointField mentioned in 12 the same as the one that now lives in django.contrib.gis? I think the PointField in comment 12 is a custom field that's different from the one in contrib.gis. It's difficult for me to tell from the comments what the issue was. In any case, I'm going to mark this as "Patch needs improvement" since it appears it needs additional tests. Replying to charstring: Is the PointField mentioned in 12 the same as the one that now lives in django.contrib.gis? No, it isn't. I've installed postgis for this bug. postgis points *can* be tested on equality.. the PointField in 12 uses the builtin postgres point type, *not* the postgis point type that django.crontib.gis does.
2020-08-17T04:24:39Z
3.2
["test_limit_choices_to_no_duplicates (model_forms.tests.LimitChoicesToTests)"]
["test_modelform_factory_metaclass (model_forms.tests.CustomMetaclassTestCase)", "test_bad_callback (model_forms.tests.FormFieldCallbackTests)", "Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.", "A custom formfield_callback is used if provided", "Regression for #15315: modelform_factory should accept widgets", "test_inherit_after_custom_callback (model_forms.tests.FormFieldCallbackTests)", "Regression for #19733", "test_custom_error_messages (model_forms.tests.ModelFormCustomErrorTests)", "test_model_clean_error_messages (model_forms.tests.ModelFormCustomErrorTests)", "test_setattr_raises_validation_error_field_specific (model_forms.tests.StrictAssignmentTests)", "test_setattr_raises_validation_error_non_field (model_forms.tests.StrictAssignmentTests)", "test_notrequired_overrides_notblank (model_forms.tests.ValidationTest)", "test_validates_with_replaced_field_excluded (model_forms.tests.ValidationTest)", "test_validates_with_replaced_field_not_specified (model_forms.tests.ValidationTest)", "test_override_clean (model_forms.tests.CustomCleanTests)", "test_field_removal (model_forms.tests.ModelFormInheritanceTests)", "test_field_removal_name_clashes (model_forms.tests.ModelFormInheritanceTests)", "test_form_subclass_inheritance (model_forms.tests.ModelFormInheritanceTests)", "test_model_form_applies_localize_to_all_fields (model_forms.tests.LocalizedModelFormTest)", "test_model_form_applies_localize_to_some_fields (model_forms.tests.LocalizedModelFormTest)", "test_model_form_refuses_arbitrary_string (model_forms.tests.LocalizedModelFormTest)", "Data for a ManyToManyField is a list rather than a lazy QuerySet.", "test_callable_called_each_time_form_is_instantiated (model_forms.tests.LimitChoicesToTests)", "test_custom_field_with_queryset_but_no_limit_choices_to (model_forms.tests.LimitChoicesToTests)", "test_fields_for_model_applies_limit_choices_to (model_forms.tests.LimitChoicesToTests)", "test_limit_choices_to_callable_for_fk_rel (model_forms.tests.LimitChoicesToTests)", "test_limit_choices_to_callable_for_m2m_rel (model_forms.tests.LimitChoicesToTests)", "test_assignment_of_none (model_forms.tests.ModelOneToOneFieldTests)", "test_assignment_of_none_null_false (model_forms.tests.ModelOneToOneFieldTests)", "test_modelform_onetoonefield (model_forms.tests.ModelOneToOneFieldTests)", "test_modelform_subclassed_model (model_forms.tests.ModelOneToOneFieldTests)", "test_onetoonefield (model_forms.tests.ModelOneToOneFieldTests)", "test_article_form (model_forms.tests.ModelFormBaseTest)", "test_bad_form (model_forms.tests.ModelFormBaseTest)", "test_base_form (model_forms.tests.ModelFormBaseTest)", "test_blank_false_with_null_true_foreign_key_field (model_forms.tests.ModelFormBaseTest)", "test_blank_foreign_key_with_radio (model_forms.tests.ModelFormBaseTest)", "test_blank_with_null_foreign_key_field (model_forms.tests.ModelFormBaseTest)", "test_confused_form (model_forms.tests.ModelFormBaseTest)", "test_default_filefield (model_forms.tests.ModelFormBaseTest)", "test_default_not_populated_on_checkboxselectmultiple (model_forms.tests.ModelFormBaseTest)", "test_default_not_populated_on_non_empty_value_in_cleaned_data (model_forms.tests.ModelFormBaseTest)", "test_default_not_populated_on_optional_checkbox_input (model_forms.tests.ModelFormBaseTest)", "test_default_not_populated_on_selectmultiple (model_forms.tests.ModelFormBaseTest)", "test_default_populated_on_optional_field (model_forms.tests.ModelFormBaseTest)", "test_default_selectdatewidget (model_forms.tests.ModelFormBaseTest)", "test_default_splitdatetime_field (model_forms.tests.ModelFormBaseTest)", "test_empty_fields_on_modelform (model_forms.tests.ModelFormBaseTest)", "test_empty_fields_to_construct_instance (model_forms.tests.ModelFormBaseTest)", "test_empty_fields_to_fields_for_model (model_forms.tests.ModelFormBaseTest)", "test_exclude_and_validation (model_forms.tests.ModelFormBaseTest)", "test_exclude_fields (model_forms.tests.ModelFormBaseTest)", "test_exclude_fields_with_string (model_forms.tests.ModelFormBaseTest)", "test_exclude_nonexistent_field (model_forms.tests.ModelFormBaseTest)", "test_extra_declared_field_model_form (model_forms.tests.ModelFormBaseTest)", "test_extra_field_model_form (model_forms.tests.ModelFormBaseTest)", "test_extra_field_modelform_factory (model_forms.tests.ModelFormBaseTest)", "test_extra_fields (model_forms.tests.ModelFormBaseTest)", "test_invalid_meta_model (model_forms.tests.ModelFormBaseTest)", "test_limit_fields_with_string (model_forms.tests.ModelFormBaseTest)", "test_limit_nonexistent_field (model_forms.tests.ModelFormBaseTest)", "test_missing_fields_attribute (model_forms.tests.ModelFormBaseTest)", "test_mixmodel_form (model_forms.tests.ModelFormBaseTest)", "test_no_model_class (model_forms.tests.ModelFormBaseTest)", "test_non_blank_foreign_key_with_radio (model_forms.tests.ModelFormBaseTest)", "test_orderfields2_form (model_forms.tests.ModelFormBaseTest)", "test_orderfields_form (model_forms.tests.ModelFormBaseTest)", "test_override_field (model_forms.tests.ModelFormBaseTest)", "test_prefixed_form_with_default_field (model_forms.tests.ModelFormBaseTest)", "test_renderer_kwarg (model_forms.tests.ModelFormBaseTest)", "test_replace_field (model_forms.tests.ModelFormBaseTest)", "test_replace_field_variant_2 (model_forms.tests.ModelFormBaseTest)", "test_replace_field_variant_3 (model_forms.tests.ModelFormBaseTest)", "test_save_blank_false_with_required_false (model_forms.tests.ModelFormBaseTest)", "test_save_blank_null_unique_charfield_saves_null (model_forms.tests.ModelFormBaseTest)", "test_subcategory_form (model_forms.tests.ModelFormBaseTest)", "test_subclassmeta_form (model_forms.tests.ModelFormBaseTest)", "test_callable_field_default (model_forms.tests.OtherModelFormTests)", "test_choices_type (model_forms.tests.OtherModelFormTests)", "test_foreignkeys_which_use_to_field (model_forms.tests.OtherModelFormTests)", "test_iterable_model_m2m (model_forms.tests.OtherModelFormTests)", "test_media_on_modelform (model_forms.tests.OtherModelFormTests)", "test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields (model_forms.tests.OtherModelFormTests)", "test_prefetch_related_queryset (model_forms.tests.OtherModelFormTests)", "test_clean_does_deduplicate_values (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_model_multiple_choice_field (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_model_multiple_choice_field_22745 (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_model_multiple_choice_number_of_queries (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_model_multiple_choice_required_false (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_model_multiple_choice_run_validators (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_model_multiple_choice_show_hidden_initial (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_show_hidden_initial_changed_queries_efficiently (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_to_field_name_with_initial_data (model_forms.tests.ModelMultipleChoiceFieldTests)", "test_big_integer_field (model_forms.tests.ModelOtherFieldTests)", "test_http_prefixing (model_forms.tests.ModelOtherFieldTests)", "test_modelform_non_editable_field (model_forms.tests.ModelOtherFieldTests)", "Check basic URL field validation on model forms", "test_error_messages_overrides (model_forms.tests.TestFieldOverridesByFormMeta)", "test_field_type_overrides (model_forms.tests.TestFieldOverridesByFormMeta)", "test_help_text_overrides (model_forms.tests.TestFieldOverridesByFormMeta)", "test_label_overrides (model_forms.tests.TestFieldOverridesByFormMeta)", "test_widget_overrides (model_forms.tests.TestFieldOverridesByFormMeta)", "test_abstract_inherited_unique (model_forms.tests.UniqueTest)", "test_abstract_inherited_unique_together (model_forms.tests.UniqueTest)", "Ensure keys and blank character strings are tested for uniqueness.", "Test for primary_key being in the form and failing validation.", "test_inherited_unique (model_forms.tests.UniqueTest)", "test_inherited_unique_for_date (model_forms.tests.UniqueTest)", "test_inherited_unique_together (model_forms.tests.UniqueTest)", "test_multiple_field_unique_together (model_forms.tests.UniqueTest)", "test_override_unique_for_date_message (model_forms.tests.UniqueTest)", "test_override_unique_message (model_forms.tests.UniqueTest)", "test_override_unique_together_message (model_forms.tests.UniqueTest)", "test_simple_unique (model_forms.tests.UniqueTest)", "test_unique_for_date (model_forms.tests.UniqueTest)", "test_unique_for_date_in_exclude (model_forms.tests.UniqueTest)", "test_unique_for_date_with_nullable_date (model_forms.tests.UniqueTest)", "test_unique_null (model_forms.tests.UniqueTest)", "ModelForm test of unique_together constraint", "test_unique_together_exclusion (model_forms.tests.UniqueTest)", "test_auto_id (model_forms.tests.ModelFormBasicTests)", "test_base_form (model_forms.tests.ModelFormBasicTests)", "test_basic_creation (model_forms.tests.ModelFormBasicTests)", "test_custom_form_fields (model_forms.tests.ModelFormBasicTests)", "test_initial_values (model_forms.tests.ModelFormBasicTests)", "test_m2m_editing (model_forms.tests.ModelFormBasicTests)", "test_m2m_initial_callable (model_forms.tests.ModelFormBasicTests)", "test_multi_fields (model_forms.tests.ModelFormBasicTests)", "test_recleaning_model_form_instance (model_forms.tests.ModelFormBasicTests)", "test_runtime_choicefield_populated (model_forms.tests.ModelFormBasicTests)", "test_save_commit_false (model_forms.tests.ModelFormBasicTests)", "test_save_with_data_errors (model_forms.tests.ModelFormBasicTests)", "test_subset_fields (model_forms.tests.ModelFormBasicTests)", "test_validate_foreign_key_to_model_with_overridden_manager (model_forms.tests.ModelFormBasicTests)", "test_validate_foreign_key_uses_default_manager (model_forms.tests.ModelFormBasicTests)", "test_clean_false (model_forms.tests.FileAndImageFieldTests)", "test_clean_false_required (model_forms.tests.FileAndImageFieldTests)", "test_clear_and_file_contradiction (model_forms.tests.FileAndImageFieldTests)", "test_custom_file_field_save (model_forms.tests.FileAndImageFieldTests)", "test_file_field_data (model_forms.tests.FileAndImageFieldTests)", "test_file_field_multiple_save (model_forms.tests.FileAndImageFieldTests)", "FilePathField(blank=True) includes the empty option.", "test_filefield_required_false (model_forms.tests.FileAndImageFieldTests)", "test_full_clear (model_forms.tests.FileAndImageFieldTests)", "test_image_field (model_forms.tests.FileAndImageFieldTests)", "test_render_empty_file_field (model_forms.tests.FileAndImageFieldTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django__django-12708
can identify rooot cause
0
django/db/backends/base/schema.py
django/django
447980e72ac01da1594dd3373a03ba40b7ee6f80
diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -393,7 +393,12 @@ def alter_index_together(self, model, old_index_together, new_index_together): news = {tuple(fields) for fields in new_index_together} # Deleted indexes for fields in olds.difference(news): - self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index) + self._delete_composed_index( + model, + fields, + {'index': True, 'unique': False}, + self.sql_delete_index, + ) # Created indexes for field_names in news.difference(olds): fields = [model._meta.get_field(field) for field in field_names]
diff --git a/tests/migrations/test_base.py b/tests/migrations/test_base.py --- a/tests/migrations/test_base.py +++ b/tests/migrations/test_base.py @@ -62,7 +62,11 @@ def assertIndexExists(self, table, columns, value=True, using='default', index_t any( c["index"] for c in connections[using].introspection.get_constraints(cursor, table).values() - if c['columns'] == list(columns) and (index_type is None or c['type'] == index_type) + if ( + c['columns'] == list(columns) and + (index_type is None or c['type'] == index_type) and + not c['unique'] + ) ), ) @@ -80,6 +84,14 @@ def assertConstraintExists(self, table, name, value=True, using='default'): def assertConstraintNotExists(self, table, name): return self.assertConstraintExists(table, name, False) + def assertUniqueConstraintExists(self, table, columns, value=True, using='default'): + with connections[using].cursor() as cursor: + constraints = connections[using].introspection.get_constraints(cursor, table).values() + self.assertEqual( + value, + any(c['unique'] for c in constraints if c['columns'] == list(columns)), + ) + def assertFKExists(self, table, columns, to, value=True, using='default'): with connections[using].cursor() as cursor: self.assertEqual( diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -1759,6 +1759,29 @@ def test_alter_index_together_remove(self): operation = migrations.AlterIndexTogether("Pony", None) self.assertEqual(operation.describe(), "Alter index_together for Pony (0 constraint(s))") + @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') + def test_alter_index_together_remove_with_unique_together(self): + app_label = 'test_alintoremove_wunto' + table_name = '%s_pony' % app_label + project_state = self.set_up_test_model(app_label, unique_together=True) + self.assertUniqueConstraintExists(table_name, ['pink', 'weight']) + # Add index together. + new_state = project_state.clone() + operation = migrations.AlterIndexTogether('Pony', [('pink', 'weight')]) + operation.state_forwards(app_label, new_state) + with connection.schema_editor() as editor: + operation.database_forwards(app_label, editor, project_state, new_state) + self.assertIndexExists(table_name, ['pink', 'weight']) + # Remove index together. + project_state = new_state + new_state = project_state.clone() + operation = migrations.AlterIndexTogether('Pony', set()) + operation.state_forwards(app_label, new_state) + with connection.schema_editor() as editor: + operation.database_forwards(app_label, editor, project_state, new_state) + self.assertIndexNotExists(table_name, ['pink', 'weight']) + self.assertUniqueConstraintExists(table_name, ['pink', 'weight']) + @skipUnlessDBFeature('supports_table_check_constraints') def test_add_constraint(self): project_state = self.set_up_test_model("test_addconstraint")
Migration crashes deleting an index_together if there is a unique_together on the same fields Description Happens with Django 1.11.10 Steps to reproduce: 1) Create models with 2 fields, add 2 same fields to unique_together and to index_together 2) Delete index_together -> Fail It will fail at django/db/backends/base/schema.py, line 378, in _delete_composed_index(), ValueError: Found wrong number (2) of constraints for as this one will find two constraints, the _uniq and the _idx one. No way to get out of this... The worst in my case is that happened as I wanted to refactor my code to use the "new" (Dj 1.11) Options.indexes feature. I am actually not deleting the index, just the way it is declared in my code. I think there are 2 different points here: 1) The deletion of index_together should be possible alone or made coherent (migrations side?) with unique_together 2) Moving the declaration of an index should not result in an index re-creation
Reproduced on master at 623139b5d1bd006eac78b375bcaf5948e695c3c6. I haven't looked under the hood on this yet, but could it be related to the ordering of the operations generated for the mgiration? on first inspection it feels like this and #28862 could be caused by the same/similar underlying problem in how FieldRelatedOptionOperation subclasses ordering is handled in the migration autodetector's migration optimizer.
2020-04-12T22:20:59Z
3.1
["test_alter_index_together_remove_with_unique_together (migrations.test_operations.OperationTests)"]
["test_references_model_mixin (migrations.test_operations.TestCreateModel)", "test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_name (migrations.test_operations.FieldOperationTests)", "test_references_field_by_remote_field_model (migrations.test_operations.FieldOperationTests)", "test_references_field_by_through (migrations.test_operations.FieldOperationTests)", "test_references_field_by_to_fields (migrations.test_operations.FieldOperationTests)", "test_references_model (migrations.test_operations.FieldOperationTests)", "test_add_field_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_create_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_delete_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_indexes_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_add_binaryfield (migrations.test_operations.OperationTests)", "test_add_charfield (migrations.test_operations.OperationTests)", "test_add_constraint (migrations.test_operations.OperationTests)", "test_add_constraint_combinable (migrations.test_operations.OperationTests)", "test_add_constraint_percent_escaping (migrations.test_operations.OperationTests)", "test_add_field (migrations.test_operations.OperationTests)", "test_add_field_m2m (migrations.test_operations.OperationTests)", "test_add_field_preserve_default (migrations.test_operations.OperationTests)", "test_add_index (migrations.test_operations.OperationTests)", "test_add_index_state_forwards (migrations.test_operations.OperationTests)", "test_add_or_constraint (migrations.test_operations.OperationTests)", "test_add_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_add_textfield (migrations.test_operations.OperationTests)", "test_alter_field (migrations.test_operations.OperationTests)", "test_alter_field_m2m (migrations.test_operations.OperationTests)", "test_alter_field_pk (migrations.test_operations.OperationTests)", "test_alter_field_pk_fk (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_target_changes (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_with_index (migrations.test_operations.OperationTests)", "test_alter_fk (migrations.test_operations.OperationTests)", "test_alter_fk_non_fk (migrations.test_operations.OperationTests)", "test_alter_index_together (migrations.test_operations.OperationTests)", "test_alter_index_together_remove (migrations.test_operations.OperationTests)", "test_alter_model_managers (migrations.test_operations.OperationTests)", "test_alter_model_managers_emptying (migrations.test_operations.OperationTests)", "test_alter_model_options (migrations.test_operations.OperationTests)", "test_alter_model_options_emptying (migrations.test_operations.OperationTests)", "test_alter_model_table (migrations.test_operations.OperationTests)", "test_alter_model_table_m2m (migrations.test_operations.OperationTests)", "test_alter_model_table_none (migrations.test_operations.OperationTests)", "test_alter_model_table_noop (migrations.test_operations.OperationTests)", "test_alter_order_with_respect_to (migrations.test_operations.OperationTests)", "test_alter_unique_together (migrations.test_operations.OperationTests)", "test_alter_unique_together_remove (migrations.test_operations.OperationTests)", "A field may be migrated from AutoField to BigAutoField.", "test_column_name_quoting (migrations.test_operations.OperationTests)", "test_create_model (migrations.test_operations.OperationTests)", "test_create_model_inheritance (migrations.test_operations.OperationTests)", "test_create_model_m2m (migrations.test_operations.OperationTests)", "test_create_model_managers (migrations.test_operations.OperationTests)", "test_create_model_with_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_base (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_field_name (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_manager_name (migrations.test_operations.OperationTests)", "test_create_model_with_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_unique_after (migrations.test_operations.OperationTests)", "test_create_proxy_model (migrations.test_operations.OperationTests)", "test_create_unmanaged_model (migrations.test_operations.OperationTests)", "test_delete_model (migrations.test_operations.OperationTests)", "test_delete_mti_model (migrations.test_operations.OperationTests)", "test_delete_proxy_model (migrations.test_operations.OperationTests)", "test_model_with_bigautofield (migrations.test_operations.OperationTests)", "test_remove_constraint (migrations.test_operations.OperationTests)", "test_remove_field (migrations.test_operations.OperationTests)", "test_remove_field_m2m (migrations.test_operations.OperationTests)", "test_remove_field_m2m_with_through (migrations.test_operations.OperationTests)", "test_remove_fk (migrations.test_operations.OperationTests)", "test_remove_index (migrations.test_operations.OperationTests)", "test_remove_index_state_forwards (migrations.test_operations.OperationTests)", "test_remove_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_rename_field (migrations.test_operations.OperationTests)", "test_rename_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)", "RenameModel renames a many-to-many column after a RenameField.", "test_rename_m2m_target_model (migrations.test_operations.OperationTests)", "test_rename_m2m_through_model (migrations.test_operations.OperationTests)", "test_rename_missing_field (migrations.test_operations.OperationTests)", "test_rename_model (migrations.test_operations.OperationTests)", "test_rename_model_state_forwards (migrations.test_operations.OperationTests)", "test_rename_model_with_m2m (migrations.test_operations.OperationTests)", "test_rename_model_with_self_referential_fk (migrations.test_operations.OperationTests)", "test_rename_model_with_self_referential_m2m (migrations.test_operations.OperationTests)", "test_rename_model_with_superclass_fk (migrations.test_operations.OperationTests)", "test_rename_referenced_field_state_forward (migrations.test_operations.OperationTests)", "test_repoint_field_m2m (migrations.test_operations.OperationTests)", "test_run_python (migrations.test_operations.OperationTests)", "test_run_python_atomic (migrations.test_operations.OperationTests)", "test_run_python_noop (migrations.test_operations.OperationTests)", "test_run_python_related_assignment (migrations.test_operations.OperationTests)", "test_run_sql (migrations.test_operations.OperationTests)", "test_run_sql_noop (migrations.test_operations.OperationTests)", "test_run_sql_params (migrations.test_operations.OperationTests)", "test_run_sql_params_invalid (migrations.test_operations.OperationTests)", "test_separate_database_and_state (migrations.test_operations.OperationTests)", "test_separate_database_and_state2 (migrations.test_operations.OperationTests)", "A field may be migrated from SmallAutoField to AutoField.", "A field may be migrated from SmallAutoField to BigAutoField."]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django__django-14730
need to identify ManyToManyField
0
django/db/models/fields/related.py
django/django
4fe3774c729f3fd5105b3001fe69a70bdca95ac3
diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -1258,6 +1258,16 @@ def _check_ignored_options(self, **kwargs): ) ) + if self.remote_field.symmetrical and self._related_name: + warnings.append( + checks.Warning( + 'related_name has no effect on ManyToManyField ' + 'with a symmetrical relationship, e.g. to "self".', + obj=self, + id='fields.W345', + ) + ) + return warnings def _check_relationship_model(self, from_model=None, **kwargs):
diff --git a/tests/field_deconstruction/tests.py b/tests/field_deconstruction/tests.py --- a/tests/field_deconstruction/tests.py +++ b/tests/field_deconstruction/tests.py @@ -438,7 +438,6 @@ class MyModel(models.Model): m2m = models.ManyToManyField('self') m2m_related_name = models.ManyToManyField( 'self', - related_name='custom_name', related_query_name='custom_query_name', limit_choices_to={'flag': True}, ) @@ -455,7 +454,6 @@ class MyModel(models.Model): self.assertEqual(args, []) self.assertEqual(kwargs, { 'to': 'field_deconstruction.MyModel', - 'related_name': 'custom_name', 'related_query_name': 'custom_query_name', 'limit_choices_to': {'flag': True}, }) diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py --- a/tests/invalid_models_tests/test_relative_fields.py +++ b/tests/invalid_models_tests/test_relative_fields.py @@ -128,6 +128,20 @@ class ThroughModel(models.Model): ), ]) + def test_many_to_many_with_useless_related_name(self): + class ModelM2M(models.Model): + m2m = models.ManyToManyField('self', related_name='children') + + field = ModelM2M._meta.get_field('m2m') + self.assertEqual(ModelM2M.check(), [ + DjangoWarning( + 'related_name has no effect on ManyToManyField with ' + 'a symmetrical relationship, e.g. to "self".', + obj=field, + id='fields.W345', + ), + ]) + def test_ambiguous_relationship_model_from(self): class Person(models.Model): pass diff --git a/tests/model_meta/models.py b/tests/model_meta/models.py --- a/tests/model_meta/models.py +++ b/tests/model_meta/models.py @@ -23,7 +23,7 @@ class AbstractPerson(models.Model): # M2M fields m2m_abstract = models.ManyToManyField(Relation, related_name='m2m_abstract_rel') - friends_abstract = models.ManyToManyField('self', related_name='friends_abstract', symmetrical=True) + friends_abstract = models.ManyToManyField('self', symmetrical=True) following_abstract = models.ManyToManyField('self', related_name='followers_abstract', symmetrical=False) # VIRTUAL fields @@ -60,7 +60,7 @@ class BasePerson(AbstractPerson): # M2M fields m2m_base = models.ManyToManyField(Relation, related_name='m2m_base_rel') - friends_base = models.ManyToManyField('self', related_name='friends_base', symmetrical=True) + friends_base = models.ManyToManyField('self', symmetrical=True) following_base = models.ManyToManyField('self', related_name='followers_base', symmetrical=False) # VIRTUAL fields @@ -88,7 +88,7 @@ class Person(BasePerson): # M2M Fields m2m_inherited = models.ManyToManyField(Relation, related_name='m2m_concrete_rel') - friends_inherited = models.ManyToManyField('self', related_name='friends_concrete', symmetrical=True) + friends_inherited = models.ManyToManyField('self', symmetrical=True) following_inherited = models.ManyToManyField('self', related_name='followers_concrete', symmetrical=False) # VIRTUAL fields
Prevent developers from defining a related_name on symmetrical ManyToManyFields Description In ManyToManyField, if the symmetrical argument is passed, or if it's a self-referential ManyToMany relationship, the related field on the target model is not created. However, if a developer passes in the related_name not understanding this fact, they may be confused until they find the information about symmetrical relationship. Thus, it is proposed to raise an error when the user defines a ManyToManyField in this condition.
I have a PR that implements this incoming. ​https://github.com/django/django/pull/14730 OK, I guess we can do something here — it probably is a source of confusion. The same issue was raised in #18021 (but as an invalid bug report, rather than suggesting improving the messaging). Looking at the PR — I'm sceptical about just raising an error — this will likely break code in the wild. Can we investigate adding a system check here instead? There are several similar checks for related fields already: ​https://docs.djangoproject.com/en/3.2/ref/checks/#related-fields Same issue also came up in #12641 Absolutely. A system check is a much better approach than my initial idea of the error. I have changed the patch to use a system check. Unchecking patch needs improvement as instructed on the page, (pending reviewer acceptance of course).
2021-08-03T04:27:52Z
4.0
["test_many_to_many_with_useless_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)"]
["test_accessor_clash (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)", "test_clash_under_explicit_related_name (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)", "test_reverse_query_name_clash (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)", "test_clash_parent_link (invalid_models_tests.test_relative_fields.ComplexClashTests)", "test_complex_clash (invalid_models_tests.test_relative_fields.ComplexClashTests)", "If ``through_fields`` kwarg is given, it must specify both", "test_intersection_foreign_object (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)", "Providing invalid field names to ManyToManyField.through_fields", "Mixing up the order of link fields to ManyToManyField.through_fields", "ManyToManyField accepts the ``through_fields`` kwarg", "test_superset_foreign_object (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)", "test_accessor_clash (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_clash_between_accessors (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_clash_under_explicit_related_name (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_reverse_query_name_clash (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_valid_model (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_clash_between_accessors (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.AccessorClashTests)", "Ref #22047.", "test_no_clash_for_hidden_related_name (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_no_clash_across_apps_without_accessor (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_ambiguous_relationship_model_from (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_ambiguous_relationship_model_to (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_abstract_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "#25723 - Referenced model registration lookup should be run against the", "test_foreign_key_to_missing_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_non_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_non_unique_field_under_explicit_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_partially_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_unique_field_with_meta_constraint (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_object_to_non_unique_fields (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_object_to_partially_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_object_to_unique_field_with_meta_constraint (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_invalid_related_query_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_m2m_to_abstract_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "#25723 - Through model registration lookup should be run against the", "test_many_to_many_to_missing_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_many_to_many_with_limit_choices_auto_created_no_warning (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_many_to_many_with_useless_options (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_missing_relationship_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_missing_relationship_model_on_model_check (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_not_swapped_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_nullable_primary_key (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_on_delete_set_default_without_default_value (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_on_delete_set_null_on_non_nullable_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_referencing_to_swapped_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_related_field_has_invalid_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_related_field_has_valid_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_relationship_model_missing_foreign_key (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_relationship_model_with_foreign_key_to_wrong_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_to_fields_exist (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_to_fields_not_checked_if_related_model_doesnt_exist (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_too_many_foreign_keys_in_self_referential_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_unique_m2m (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_valid_foreign_key_without_accessor (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_auto_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_big_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_binary_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_boolean_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_char_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_char_field_choices (field_deconstruction.tests.FieldDeconstructionTests)", "test_csi_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_date_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_datetime_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_db_tablespace (field_deconstruction.tests.FieldDeconstructionTests)", "test_decimal_field (field_deconstruction.tests.FieldDeconstructionTests)", "A DecimalField with decimal_places=0 should work (#22272).", "test_email_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_file_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_file_path_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_float_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_foreign_key (field_deconstruction.tests.FieldDeconstructionTests)", "test_foreign_key_swapped (field_deconstruction.tests.FieldDeconstructionTests)", "test_generic_ip_address_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_image_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_ip_address_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_many_to_many_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_many_to_many_field_related_name (field_deconstruction.tests.FieldDeconstructionTests)", "test_many_to_many_field_swapped (field_deconstruction.tests.FieldDeconstructionTests)", "Tests the outputting of the correct name if assigned one.", "test_one_to_one (field_deconstruction.tests.FieldDeconstructionTests)", "test_positive_big_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_positive_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_positive_small_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_slug_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_small_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_text_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_time_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_url_field (field_deconstruction.tests.FieldDeconstructionTests)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-13551
easy after identifying _make_hash_value
0
django/contrib/auth/tokens.py
django/django
7f9e4524d6b23424cf44fbe1bf1f4e70f6bb066e
diff --git a/django/contrib/auth/tokens.py b/django/contrib/auth/tokens.py --- a/django/contrib/auth/tokens.py +++ b/django/contrib/auth/tokens.py @@ -78,9 +78,9 @@ def _make_token_with_timestamp(self, user, timestamp, legacy=False): def _make_hash_value(self, user, timestamp): """ - Hash the user's primary key and some user state that's sure to change - after a password reset to produce a token that invalidated when it's - used: + Hash the user's primary key, email (if available), and some user state + that's sure to change after a password reset to produce a token that is + invalidated when it's used: 1. The password field will change upon a password reset (even if the same password is chosen, due to password salting). 2. The last_login field will usually be updated very shortly after @@ -94,7 +94,9 @@ def _make_hash_value(self, user, timestamp): # Truncate microseconds so that tokens are consistent even if the # database doesn't support microseconds. login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) - return str(user.pk) + user.password + str(login_timestamp) + str(timestamp) + email_field = user.get_email_field_name() + email = getattr(user, email_field, '') or '' + return f'{user.pk}{user.password}{login_timestamp}{timestamp}{email}' def _num_seconds(self, dt): return int((dt - datetime(2001, 1, 1)).total_seconds())
diff --git a/tests/auth_tests/models/__init__.py b/tests/auth_tests/models/__init__.py --- a/tests/auth_tests/models/__init__.py +++ b/tests/auth_tests/models/__init__.py @@ -8,6 +8,7 @@ from .no_password import NoPasswordUser from .proxy import Proxy, UserProxy from .uuid_pk import UUIDUser +from .with_custom_email_field import CustomEmailField from .with_foreign_key import CustomUserWithFK, Email from .with_integer_username import IntegerUsernameUser from .with_last_login_attr import UserWithDisabledLastLoginField @@ -16,10 +17,10 @@ ) __all__ = ( - 'CustomPermissionsUser', 'CustomUser', 'CustomUserNonUniqueUsername', - 'CustomUserWithFK', 'CustomUserWithM2M', 'CustomUserWithM2MThrough', - 'CustomUserWithoutIsActiveField', 'Email', 'ExtensionUser', - 'IntegerUsernameUser', 'IsActiveTestUser1', 'MinimalUser', + 'CustomEmailField', 'CustomPermissionsUser', 'CustomUser', + 'CustomUserNonUniqueUsername', 'CustomUserWithFK', 'CustomUserWithM2M', + 'CustomUserWithM2MThrough', 'CustomUserWithoutIsActiveField', 'Email', + 'ExtensionUser', 'IntegerUsernameUser', 'IsActiveTestUser1', 'MinimalUser', 'NoPasswordUser', 'Organization', 'Proxy', 'UUIDUser', 'UserProxy', 'UserWithDisabledLastLoginField', ) diff --git a/tests/auth_tests/models/with_custom_email_field.py b/tests/auth_tests/models/with_custom_email_field.py --- a/tests/auth_tests/models/with_custom_email_field.py +++ b/tests/auth_tests/models/with_custom_email_field.py @@ -15,7 +15,7 @@ def create_user(self, username, password, email): class CustomEmailField(AbstractBaseUser): username = models.CharField(max_length=255) password = models.CharField(max_length=255) - email_address = models.EmailField() + email_address = models.EmailField(null=True) is_active = models.BooleanField(default=True) EMAIL_FIELD = 'email_address' diff --git a/tests/auth_tests/test_models.py b/tests/auth_tests/test_models.py --- a/tests/auth_tests/test_models.py +++ b/tests/auth_tests/test_models.py @@ -17,8 +17,7 @@ SimpleTestCase, TestCase, TransactionTestCase, override_settings, ) -from .models import IntegerUsernameUser -from .models.with_custom_email_field import CustomEmailField +from .models import CustomEmailField, IntegerUsernameUser class NaturalKeysTestCase(TestCase): diff --git a/tests/auth_tests/test_tokens.py b/tests/auth_tests/test_tokens.py --- a/tests/auth_tests/test_tokens.py +++ b/tests/auth_tests/test_tokens.py @@ -7,6 +7,8 @@ from django.test.utils import ignore_warnings from django.utils.deprecation import RemovedInDjango40Warning +from .models import CustomEmailField + class MockedPasswordResetTokenGenerator(PasswordResetTokenGenerator): def __init__(self, now): @@ -37,6 +39,27 @@ def test_10265(self): tk2 = p0.make_token(user_reload) self.assertEqual(tk1, tk2) + def test_token_with_different_email(self): + """Updating the user email address invalidates the token.""" + tests = [ + (CustomEmailField, None), + (CustomEmailField, 'test4@example.com'), + (User, 'test4@example.com'), + ] + for model, email in tests: + with self.subTest(model=model.__qualname__, email=email): + user = model.objects.create_user( + 'changeemailuser', + email=email, + password='testpw', + ) + p0 = PasswordResetTokenGenerator() + tk1 = p0.make_token(user) + self.assertIs(p0.check_token(user, tk1), True) + setattr(user, user.get_email_field_name(), 'test4new@example.com') + user.save() + self.assertIs(p0.check_token(user, tk1), False) + def test_timeout(self): """The token is valid after n seconds, but no greater.""" # Uses a mocked version of PasswordResetTokenGenerator so we can change
Changing user's email could invalidate password reset tokens Description Sequence: Have account with email address foo@… Password reset request for that email (unused) foo@… account changes their email address Password reset email is used The password reset email's token should be rejected at that point, but in fact it is allowed. The fix is to add the user's email address into ​PasswordResetTokenGenerator._make_hash_value() Nothing forces a user to even have an email as per AbstractBaseUser. Perhaps the token generation method could be factored out onto the model, ala get_session_auth_hash().
2020-10-17T17:22:01Z
3.2
["Updating the user email address invalidates the token.", "test_token_with_different_secret (auth_tests.test_tokens.TokenGeneratorTest)"]
["test_str (auth_tests.test_models.GroupTests)", "test_group_natural_key (auth_tests.test_models.NaturalKeysTestCase)", "test_user_natural_key (auth_tests.test_models.NaturalKeysTestCase)", "test_check_password (auth_tests.test_models.AnonymousUserTests)", "test_delete (auth_tests.test_models.AnonymousUserTests)", "test_eq (auth_tests.test_models.AnonymousUserTests)", "test_hash (auth_tests.test_models.AnonymousUserTests)", "test_int (auth_tests.test_models.AnonymousUserTests)", "test_properties (auth_tests.test_models.AnonymousUserTests)", "test_save (auth_tests.test_models.AnonymousUserTests)", "test_set_password (auth_tests.test_models.AnonymousUserTests)", "test_str (auth_tests.test_models.AnonymousUserTests)", "test_create_superuser (auth_tests.test_models.TestCreateSuperUserSignals)", "test_create_user (auth_tests.test_models.TestCreateSuperUserSignals)", "test_str (auth_tests.test_models.PermissionTests)", "test_load_data_with_user_permissions (auth_tests.test_models.LoadDataWithNaturalKeysAndMultipleDatabasesTestCase)", "test_10265 (auth_tests.test_tokens.TokenGeneratorTest)", "test_check_token_with_nonexistent_token_and_user (auth_tests.test_tokens.TokenGeneratorTest)", "test_legacy_token_validation (auth_tests.test_tokens.TokenGeneratorTest)", "test_make_token (auth_tests.test_tokens.TokenGeneratorTest)", "The token is valid after n seconds, but no greater.", "test_token_default_hashing_algorithm (auth_tests.test_tokens.TokenGeneratorTest)", "test_user_is_created_and_added_to_group (auth_tests.test_models.LoadDataWithNaturalKeysTestCase)", "test_user_is_created_and_added_to_group (auth_tests.test_models.LoadDataWithoutNaturalKeysTestCase)", "test_backend_without_with_perm (auth_tests.test_models.UserWithPermTestCase)", "test_basic (auth_tests.test_models.UserWithPermTestCase)", "test_custom_backend (auth_tests.test_models.UserWithPermTestCase)", "test_custom_backend_pass_obj (auth_tests.test_models.UserWithPermTestCase)", "test_invalid_backend_type (auth_tests.test_models.UserWithPermTestCase)", "test_invalid_permission_name (auth_tests.test_models.UserWithPermTestCase)", "test_invalid_permission_type (auth_tests.test_models.UserWithPermTestCase)", "test_multiple_backends (auth_tests.test_models.UserWithPermTestCase)", "test_nonexistent_backend (auth_tests.test_models.UserWithPermTestCase)", "test_nonexistent_permission (auth_tests.test_models.UserWithPermTestCase)", "test_clean_normalize_username (auth_tests.test_models.AbstractBaseUserTests)", "test_custom_email (auth_tests.test_models.AbstractBaseUserTests)", "test_default_email (auth_tests.test_models.AbstractBaseUserTests)", "test_has_usable_password (auth_tests.test_models.AbstractBaseUserTests)", "test_normalize_username (auth_tests.test_models.AbstractBaseUserTests)", "test_builtin_user_isactive (auth_tests.test_models.IsActiveTestCase)", "test_is_active_field_default (auth_tests.test_models.IsActiveTestCase)", "test_check_password_upgrade (auth_tests.test_models.AbstractUserTestCase)", "test_email_user (auth_tests.test_models.AbstractUserTestCase)", "test_last_login_default (auth_tests.test_models.AbstractUserTestCase)", "test_user_clean_normalize_email (auth_tests.test_models.AbstractUserTestCase)", "test_user_double_save (auth_tests.test_models.AbstractUserTestCase)", "test_create_super_user_raises_error_on_false_is_superuser (auth_tests.test_models.UserManagerTestCase)", "test_create_superuser_raises_error_on_false_is_staff (auth_tests.test_models.UserManagerTestCase)", "test_create_user (auth_tests.test_models.UserManagerTestCase)", "test_create_user_email_domain_normalize (auth_tests.test_models.UserManagerTestCase)", "test_create_user_email_domain_normalize_rfc3696 (auth_tests.test_models.UserManagerTestCase)", "test_create_user_email_domain_normalize_with_whitespace (auth_tests.test_models.UserManagerTestCase)", "test_create_user_is_staff (auth_tests.test_models.UserManagerTestCase)", "test_empty_username (auth_tests.test_models.UserManagerTestCase)", "test_make_random_password (auth_tests.test_models.UserManagerTestCase)", "test_runpython_manager_methods (auth_tests.test_models.UserManagerTestCase)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django__django-13933
easy after identifying ModelMultipleChoiceField
1
django/forms/models.py
django/django
42e8cf47c7ee2db238bf91197ea398126c546741
diff --git a/django/forms/models.py b/django/forms/models.py --- a/django/forms/models.py +++ b/django/forms/models.py @@ -1284,7 +1284,11 @@ def to_python(self, value): value = getattr(value, key) value = self.queryset.get(**{key: value}) except (ValueError, TypeError, self.queryset.model.DoesNotExist): - raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice') + raise ValidationError( + self.error_messages['invalid_choice'], + code='invalid_choice', + params={'value': value}, + ) return value def validate(self, value):
diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py --- a/tests/forms_tests/tests/test_error_messages.py +++ b/tests/forms_tests/tests/test_error_messages.py @@ -308,3 +308,16 @@ def test_modelchoicefield(self): self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3') self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4']) + + def test_modelchoicefield_value_placeholder(self): + f = ModelChoiceField( + queryset=ChoiceModel.objects.all(), + error_messages={ + 'invalid_choice': '"%(value)s" is not one of the available choices.', + }, + ) + self.assertFormErrors( + ['"invalid" is not one of the available choices.'], + f.clean, + 'invalid', + )
ModelChoiceField does not provide value of invalid choice when raising ValidationError Description (last modified by Aaron Wiegel) Compared with ChoiceField and others, ModelChoiceField does not show the value of the invalid choice when raising a validation error. Passing in parameters with the invalid value and modifying the default error message for the code invalid_choice should fix this. From source code: class ModelMultipleChoiceField(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" widget = SelectMultiple hidden_widget = MultipleHiddenInput default_error_messages = { 'invalid_list': _('Enter a list of values.'), 'invalid_choice': _('Select a valid choice. %(value)s is not one of the' ' available choices.'), 'invalid_pk_value': _('“%(pk)s” is not a valid value.') } ... class ModelChoiceField(ChoiceField): """A ChoiceField whose choices are a model QuerySet.""" # This class is a subclass of ChoiceField for purity, but it doesn't # actually use any of ChoiceField's implementation. default_error_messages = { 'invalid_choice': _('Select a valid choice. That choice is not one of' ' the available choices.'), } ...
This message has been the same literally forever b2b6fc8e3c78671c8b6af2709358c3213c84d119. ​Given that ChoiceField passes the value when raising the error, if you set ​error_messages you should be able to get the result you want. Replying to Carlton Gibson: This message has been the same literally forever b2b6fc8e3c78671c8b6af2709358c3213c84d119. ​Given that ChoiceField passes the value when raising the error, if you set ​error_messages you should be able to get the result you want. That is ChoiceField. ModelChoiceField ​does not pass the value to the validation error. So, when the invalid value error is raised, you can't display the offending value even if you override the defaults. OK, if you want to look at submitting a PR we can see if any objections come up in review. Thanks. PR: ​https://github.com/django/django/pull/13933
2021-01-26T03:58:23Z
4.0
["test_modelchoicefield_value_placeholder (forms_tests.tests.test_error_messages.ModelChoiceFieldErrorMessagesTestCase)"]
["test_modelchoicefield (forms_tests.tests.test_error_messages.ModelChoiceFieldErrorMessagesTestCase)", "test_booleanfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_charfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_choicefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_datefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_datetimefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_decimalfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_emailfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_error_messages_escaping (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_filefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_floatfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_generic_ipaddressfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_integerfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_multiplechoicefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_regexfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_splitdatetimefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_subclassing_errorlist (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_timefield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_urlfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-13660
easy with tsacktrace
0
django/core/management/commands/shell.py
django/django
50c3ac6fa9b7c8a94a6d1dc87edf775e3bc4d575
diff --git a/django/core/management/commands/shell.py b/django/core/management/commands/shell.py --- a/django/core/management/commands/shell.py +++ b/django/core/management/commands/shell.py @@ -84,13 +84,13 @@ def python(self, options): def handle(self, **options): # Execute the command and exit. if options['command']: - exec(options['command']) + exec(options['command'], globals()) return # Execute stdin if it has anything to read and exit. # Not supported on Windows due to select.select() limitations. if sys.platform != 'win32' and not sys.stdin.isatty() and select.select([sys.stdin], [], [], 0)[0]: - exec(sys.stdin.read()) + exec(sys.stdin.read(), globals()) return available_shells = [options['interface']] if options['interface'] else self.shells
diff --git a/tests/shell/tests.py b/tests/shell/tests.py --- a/tests/shell/tests.py +++ b/tests/shell/tests.py @@ -9,6 +9,13 @@ class ShellCommandTestCase(SimpleTestCase): + script_globals = 'print("__name__" in globals())' + script_with_inline_function = ( + 'import django\n' + 'def f():\n' + ' print(django.__version__)\n' + 'f()' + ) def test_command_option(self): with self.assertLogs('test', 'INFO') as cm: @@ -21,6 +28,16 @@ def test_command_option(self): ) self.assertEqual(cm.records[0].getMessage(), __version__) + def test_command_option_globals(self): + with captured_stdout() as stdout: + call_command('shell', command=self.script_globals) + self.assertEqual(stdout.getvalue().strip(), 'True') + + def test_command_option_inline_function_call(self): + with captured_stdout() as stdout: + call_command('shell', command=self.script_with_inline_function) + self.assertEqual(stdout.getvalue().strip(), __version__) + @unittest.skipIf(sys.platform == 'win32', "Windows select() doesn't support file descriptors.") @mock.patch('django.core.management.commands.shell.select') def test_stdin_read(self, select): @@ -30,6 +47,30 @@ def test_stdin_read(self, select): call_command('shell') self.assertEqual(stdout.getvalue().strip(), '100') + @unittest.skipIf( + sys.platform == 'win32', + "Windows select() doesn't support file descriptors.", + ) + @mock.patch('django.core.management.commands.shell.select') # [1] + def test_stdin_read_globals(self, select): + with captured_stdin() as stdin, captured_stdout() as stdout: + stdin.write(self.script_globals) + stdin.seek(0) + call_command('shell') + self.assertEqual(stdout.getvalue().strip(), 'True') + + @unittest.skipIf( + sys.platform == 'win32', + "Windows select() doesn't support file descriptors.", + ) + @mock.patch('django.core.management.commands.shell.select') # [1] + def test_stdin_read_inline_function_call(self, select): + with captured_stdin() as stdin, captured_stdout() as stdout: + stdin.write(self.script_with_inline_function) + stdin.seek(0) + call_command('shell') + self.assertEqual(stdout.getvalue().strip(), __version__) + @mock.patch('django.core.management.commands.shell.select.select') # [1] @mock.patch.dict('sys.modules', {'IPython': None}) def test_shell_with_ipython_not_installed(self, select):
shell command crashes when passing (with -c) the python code with functions. Description The examples below use Python 3.7 and Django 2.2.16, but I checked that the code is the same on master and works the same in Python 3.8. Here's how ​python -c works: $ python -c <<EOF " import django def f(): print(django.__version__) f()" EOF 2.2.16 Here's how ​python -m django shell -c works (paths shortened for clarify): $ python -m django shell -c <<EOF " import django def f(): print(django.__version__) f()" EOF Traceback (most recent call last): File "{sys.base_prefix}/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "{sys.base_prefix}/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "{sys.prefix}/lib/python3.7/site-packages/django/__main__.py", line 9, in <module> management.execute_from_command_line() File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/commands/shell.py", line 86, in handle exec(options['command']) File "<string>", line 5, in <module> File "<string>", line 4, in f NameError: name 'django' is not defined The problem is in the ​usage of ​exec: def handle(self, **options): # Execute the command and exit. if options['command']: exec(options['command']) return # Execute stdin if it has anything to read and exit. # Not supported on Windows due to select.select() limitations. if sys.platform != 'win32' and not sys.stdin.isatty() and select.select([sys.stdin], [], [], 0)[0]: exec(sys.stdin.read()) return exec should be passed a dictionary containing a minimal set of globals. This can be done by just passing a new, empty dictionary as the second argument of exec.
​PR includes tests and documents the new feature in the release notes (but not in the main docs since it seems more like a bug fix than a new feature to me).
2020-11-09T22:43:32Z
3.2
["test_command_option_inline_function_call (shell.tests.ShellCommandTestCase)", "test_stdin_read_inline_function_call (shell.tests.ShellCommandTestCase)"]
["test_command_option (shell.tests.ShellCommandTestCase)", "test_command_option_globals (shell.tests.ShellCommandTestCase)", "test_shell_with_bpython_not_installed (shell.tests.ShellCommandTestCase)", "test_shell_with_ipython_not_installed (shell.tests.ShellCommandTestCase)", "test_stdin_read (shell.tests.ShellCommandTestCase)", "test_stdin_read_globals (shell.tests.ShellCommandTestCase)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django__django-16527
easy
0
django/contrib/admin/templatetags/admin_modify.py
django/django
bd366ca2aeffa869b7dbc0b0aa01caea75e6dc31
diff --git a/django/contrib/admin/templatetags/admin_modify.py b/django/contrib/admin/templatetags/admin_modify.py --- a/django/contrib/admin/templatetags/admin_modify.py +++ b/django/contrib/admin/templatetags/admin_modify.py @@ -100,7 +100,7 @@ def submit_row(context): and context.get("show_delete", True) ), "show_save_as_new": not is_popup - and has_change_permission + and has_add_permission and change and save_as, "show_save_and_add_another": can_save_and_add_another,
diff --git a/tests/admin_views/test_templatetags.py b/tests/admin_views/test_templatetags.py --- a/tests/admin_views/test_templatetags.py +++ b/tests/admin_views/test_templatetags.py @@ -3,6 +3,7 @@ from django.contrib.admin import ModelAdmin from django.contrib.admin.templatetags.admin_list import date_hierarchy from django.contrib.admin.templatetags.admin_modify import submit_row +from django.contrib.auth import get_permission_codename from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.test import RequestFactory, TestCase @@ -10,7 +11,7 @@ from .admin import ArticleAdmin, site from .models import Article, Question -from .tests import AdminViewBasicTestCase +from .tests import AdminViewBasicTestCase, get_perm class AdminTemplateTagsTest(AdminViewBasicTestCase): @@ -33,6 +34,38 @@ def test_submit_row(self): self.assertIs(template_context["extra"], True) self.assertIs(template_context["show_save"], True) + def test_submit_row_save_as_new_add_permission_required(self): + change_user = User.objects.create_user( + username="change_user", password="secret", is_staff=True + ) + change_user.user_permissions.add( + get_perm(User, get_permission_codename("change", User._meta)), + ) + request = self.request_factory.get( + reverse("admin:auth_user_change", args=[self.superuser.pk]) + ) + request.user = change_user + admin = UserAdmin(User, site) + admin.save_as = True + response = admin.change_view(request, str(self.superuser.pk)) + template_context = submit_row(response.context_data) + self.assertIs(template_context["show_save_as_new"], False) + + add_user = User.objects.create_user( + username="add_user", password="secret", is_staff=True + ) + add_user.user_permissions.add( + get_perm(User, get_permission_codename("add", User._meta)), + get_perm(User, get_permission_codename("change", User._meta)), + ) + request = self.request_factory.get( + reverse("admin:auth_user_change", args=[self.superuser.pk]) + ) + request.user = add_user + response = admin.change_view(request, str(self.superuser.pk)) + template_context = submit_row(response.context_data) + self.assertIs(template_context["show_save_as_new"], True) + def test_override_show_save_and_add_another(self): request = self.request_factory.get( reverse("admin:auth_user_change", args=[self.superuser.pk]),
"show_save_as_new" in admin can add without this permission Description (last modified by Mariusz Felisiak) At "django/contrib/admin/templatetags/admin_modify.py" file, line 102, I think you must put one more verification for this tag: "and has_add_permission", because "save_as_new" is a add modification. I rewrite this for my project: "show_save_as_new": not is_popup and has_add_permission # This line that I put!!! and has_change_permission and change and save_as,
Thanks for the report. It was previously reported in #5650 and #3817, and #3817 was closed but only with a fix for "Save and add another" (see 825f0beda804e48e9197fcf3b0d909f9f548aa47). I rewrite this for my project: "show_save_as_new": not is_popup and has_add_permission # This line that I put!!! and has_change_permission and change and save_as, Do we need to check both? Checking only has_add_permission should be enough. Replying to Neesham: Yes, because "Save as New" is a save too (current object). Oh, yes! Sorry and tanks ;-)
2023-02-05T22:05:00Z
5.0
["test_submit_row_save_as_new_add_permission_required (admin_views.test_templatetags.AdminTemplateTagsTest.test_submit_row_save_as_new_add_permission_required)"]
["test_choice_links (admin_views.test_templatetags.DateHierarchyTests.test_choice_links)", "test_choice_links_datetime (admin_views.test_templatetags.DateHierarchyTests.test_choice_links_datetime)", "admin_modify template tags follow the standard search pattern", "admin_list template tags follow the standard search pattern", "test_override_show_save_and_add_another (admin_views.test_templatetags.AdminTemplateTagsTest.test_override_show_save_and_add_another)", "submit_row template tag should pass whole context."]
4a72da71001f154ea60906a2f74898d32b7322a7
django__django-12589
file structure will help
0
django/db/models/sql/query.py
django/django
895f28f9cbed817c00ab68770433170d83132d90
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1927,6 +1927,19 @@ def set_group_by(self, allow_aliases=True): primary key, and the query would be equivalent, the optimization will be made automatically. """ + # Column names from JOINs to check collisions with aliases. + if allow_aliases: + column_names = set() + seen_models = set() + for join in list(self.alias_map.values())[1:]: # Skip base table. + model = join.join_field.related_model + if model not in seen_models: + column_names.update({ + field.column + for field in model._meta.local_concrete_fields + }) + seen_models.add(model) + group_by = list(self.select) if self.annotation_select: for alias, annotation in self.annotation_select.items(): @@ -1940,7 +1953,7 @@ def set_group_by(self, allow_aliases=True): warnings.warn(msg, category=RemovedInDjango40Warning) group_by_cols = annotation.get_group_by_cols() else: - if not allow_aliases: + if not allow_aliases or alias in column_names: alias = None group_by_cols = annotation.get_group_by_cols(alias=alias) group_by.extend(group_by_cols)
diff --git a/tests/aggregation/models.py b/tests/aggregation/models.py --- a/tests/aggregation/models.py +++ b/tests/aggregation/models.py @@ -5,6 +5,7 @@ class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) + rating = models.FloatField(null=True) def __str__(self): return self.name diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -1191,6 +1191,22 @@ def test_aggregation_subquery_annotation_values(self): }, ]) + def test_aggregation_subquery_annotation_values_collision(self): + books_rating_qs = Book.objects.filter( + publisher=OuterRef('pk'), + price=Decimal('29.69'), + ).values('rating') + publisher_qs = Publisher.objects.filter( + book__contact__age__gt=20, + name=self.p1.name, + ).annotate( + rating=Subquery(books_rating_qs), + contacts_count=Count('book__contact'), + ).values('rating').annotate(total_count=Count('rating')) + self.assertEqual(list(publisher_qs), [ + {'rating': 4.0, 'total_count': 2}, + ]) + @skipUnlessDBFeature('supports_subqueries_in_group_by') @skipIf( connection.vendor == 'mysql' and 'ONLY_FULL_GROUP_BY' in connection.sql_mode,
Django 3.0: "GROUP BY" clauses error with tricky field annotation Description Let's pretend that we have next model structure with next model's relations: class A(models.Model): bs = models.ManyToManyField('B', related_name="a", through="AB") class B(models.Model): pass class AB(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, related_name="ab_a") b = models.ForeignKey(B, on_delete=models.CASCADE, related_name="ab_b") status = models.IntegerField() class C(models.Model): a = models.ForeignKey( A, null=True, blank=True, on_delete=models.SET_NULL, related_name="c", verbose_name=_("a") ) status = models.IntegerField() Let's try to evaluate next query ab_query = AB.objects.filter(a=OuterRef("pk"), b=1) filter_conditions = Q(pk=1) | Q(ab_a__b=1) query = A.objects.\ filter(filter_conditions).\ annotate( status=Subquery(ab_query.values("status")), c_count=Count("c"), ) answer = query.values("status").annotate(total_count=Count("status")) print(answer.query) print(answer) On Django 3.0.4 we have an error django.db.utils.ProgrammingError: column reference "status" is ambiguous and query is next: SELECT (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = "test_app_a"."id" AND U0."b_id" = 1)) AS "status", COUNT((SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = "test_app_a"."id" AND U0."b_id" = 1))) AS "total_count" FROM "test_app_a" LEFT OUTER JOIN "test_app_ab" ON ("test_app_a"."id" = "test_app_ab"."a_id") LEFT OUTER JOIN "test_app_c" ON ("test_app_a"."id" = "test_app_c"."a_id") WHERE ("test_app_a"."id" = 1 OR "test_app_ab"."b_id" = 1) GROUP BY "status" However, Django 2.2.11 processed this query properly with the next query: SELECT (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1)) AS "status", COUNT((SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1))) AS "total_count" FROM "test_app_a" LEFT OUTER JOIN "test_app_ab" ON ("test_app_a"."id" = "test_app_ab"."a_id") LEFT OUTER JOIN "test_app_c" ON ("test_app_a"."id" = "test_app_c"."a_id") WHERE ("test_app_a"."id" = 1 OR "test_app_ab"."b_id" = 1) GROUP BY (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1)) so, the difference in "GROUP BY" clauses (as DB provider uses "django.db.backends.postgresql", postgresql 11)
This is due to a collision of AB.status and the status annotation. The easiest way to solve this issue is to disable group by alias when a collision is detected with involved table columns. This can be easily worked around by avoiding to use an annotation name that conflicts with involved table column names. @Simon I think we have the ​check for collision in annotation alias and model fields . How can we find the involved tables columns? Thanks Hasan this is another kind of collision, these fields are not selected and part of join tables so they won't be part of names. We can't change the behavior at the annotate() level as it would be backward incompatible and require extra checks every time an additional table is joined. What needs to be adjust is sql.Query.set_group_by to set alias=None if alias is not None and alias in {... set of all column names of tables in alias_map ...} before calling annotation.get_group_by_cols ​https://github.com/django/django/blob/fc0fa72ff4cdbf5861a366e31cb8bbacd44da22d/django/db/models/sql/query.py#L1943-L1945
2020-03-19T19:04:17Z
3.1
["test_aggregation_subquery_annotation_values_collision (aggregation.tests.AggregateTestCase)"]
["test_add_implementation (aggregation.tests.AggregateTestCase)", "test_aggregate_alias (aggregation.tests.AggregateTestCase)", "test_aggregate_annotation (aggregation.tests.AggregateTestCase)", "test_aggregate_in_order_by (aggregation.tests.AggregateTestCase)", "test_aggregate_multi_join (aggregation.tests.AggregateTestCase)", "test_aggregate_over_complex_annotation (aggregation.tests.AggregateTestCase)", "test_aggregation_exists_annotation (aggregation.tests.AggregateTestCase)", "test_aggregation_expressions (aggregation.tests.AggregateTestCase)", "test_aggregation_order_by_not_selected_annotation_values (aggregation.tests.AggregateTestCase)", "Subquery annotations are excluded from the GROUP BY if they are", "test_aggregation_subquery_annotation_exists (aggregation.tests.AggregateTestCase)", "test_aggregation_subquery_annotation_multivalued (aggregation.tests.AggregateTestCase)", "test_aggregation_subquery_annotation_related_field (aggregation.tests.AggregateTestCase)", "test_aggregation_subquery_annotation_values (aggregation.tests.AggregateTestCase)", "test_annotate_basic (aggregation.tests.AggregateTestCase)", "test_annotate_defer (aggregation.tests.AggregateTestCase)", "test_annotate_defer_select_related (aggregation.tests.AggregateTestCase)", "test_annotate_m2m (aggregation.tests.AggregateTestCase)", "test_annotate_ordering (aggregation.tests.AggregateTestCase)", "test_annotate_over_annotate (aggregation.tests.AggregateTestCase)", "test_annotate_values (aggregation.tests.AggregateTestCase)", "test_annotate_values_aggregate (aggregation.tests.AggregateTestCase)", "test_annotate_values_list (aggregation.tests.AggregateTestCase)", "test_annotated_aggregate_over_annotated_aggregate (aggregation.tests.AggregateTestCase)", "test_annotation (aggregation.tests.AggregateTestCase)", "test_annotation_expressions (aggregation.tests.AggregateTestCase)", "test_arguments_must_be_expressions (aggregation.tests.AggregateTestCase)", "test_avg_decimal_field (aggregation.tests.AggregateTestCase)", "test_avg_duration_field (aggregation.tests.AggregateTestCase)", "test_backwards_m2m_annotate (aggregation.tests.AggregateTestCase)", "test_combine_different_types (aggregation.tests.AggregateTestCase)", "test_complex_aggregations_require_kwarg (aggregation.tests.AggregateTestCase)", "test_complex_values_aggregation (aggregation.tests.AggregateTestCase)", "test_count (aggregation.tests.AggregateTestCase)", "test_count_distinct_expression (aggregation.tests.AggregateTestCase)", "test_count_star (aggregation.tests.AggregateTestCase)", "test_dates_with_aggregation (aggregation.tests.AggregateTestCase)", "test_decimal_max_digits_has_no_effect (aggregation.tests.AggregateTestCase)", "test_distinct_on_aggregate (aggregation.tests.AggregateTestCase)", "test_empty_aggregate (aggregation.tests.AggregateTestCase)", "test_even_more_aggregate (aggregation.tests.AggregateTestCase)", "test_expression_on_aggregation (aggregation.tests.AggregateTestCase)", "test_filter_aggregate (aggregation.tests.AggregateTestCase)", "test_filtering (aggregation.tests.AggregateTestCase)", "test_fkey_aggregate (aggregation.tests.AggregateTestCase)", "test_group_by_exists_annotation (aggregation.tests.AggregateTestCase)", "test_group_by_subquery_annotation (aggregation.tests.AggregateTestCase)", "test_grouped_annotation_in_group_by (aggregation.tests.AggregateTestCase)", "test_missing_output_field_raises_error (aggregation.tests.AggregateTestCase)", "test_more_aggregation (aggregation.tests.AggregateTestCase)", "test_multi_arg_aggregate (aggregation.tests.AggregateTestCase)", "test_multiple_aggregates (aggregation.tests.AggregateTestCase)", "test_non_grouped_annotation_not_in_group_by (aggregation.tests.AggregateTestCase)", "test_nonaggregate_aggregation_throws (aggregation.tests.AggregateTestCase)", "test_nonfield_annotation (aggregation.tests.AggregateTestCase)", "test_order_of_precedence (aggregation.tests.AggregateTestCase)", "test_related_aggregate (aggregation.tests.AggregateTestCase)", "test_reverse_fkey_annotate (aggregation.tests.AggregateTestCase)", "test_single_aggregate (aggregation.tests.AggregateTestCase)", "test_sum_distinct_aggregate (aggregation.tests.AggregateTestCase)", "test_sum_duration_field (aggregation.tests.AggregateTestCase)", "test_ticket11881 (aggregation.tests.AggregateTestCase)", "test_ticket12886 (aggregation.tests.AggregateTestCase)", "test_ticket17424 (aggregation.tests.AggregateTestCase)", "test_values_aggregation (aggregation.tests.AggregateTestCase)", "test_values_annotation_with_expression (aggregation.tests.AggregateTestCase)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django__django-12700
easy
0
django/views/debug.py
django/django
d51c50d836c5cf8db5566da17963f871be554615
diff --git a/django/views/debug.py b/django/views/debug.py --- a/django/views/debug.py +++ b/django/views/debug.py @@ -90,6 +90,10 @@ def cleanse_setting(self, key, value): cleansed = self.cleansed_substitute elif isinstance(value, dict): cleansed = {k: self.cleanse_setting(k, v) for k, v in value.items()} + elif isinstance(value, list): + cleansed = [self.cleanse_setting('', v) for v in value] + elif isinstance(value, tuple): + cleansed = tuple([self.cleanse_setting('', v) for v in value]) else: cleansed = value except TypeError:
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 @@ -1249,6 +1249,41 @@ def test_cleanse_setting_recurses_in_dictionary(self): {'login': 'cooper', 'password': reporter_filter.cleansed_substitute}, ) + def test_cleanse_setting_recurses_in_list_tuples(self): + reporter_filter = SafeExceptionReporterFilter() + initial = [ + { + 'login': 'cooper', + 'password': 'secret', + 'apps': ( + {'name': 'app1', 'api_key': 'a06b-c462cffae87a'}, + {'name': 'app2', 'api_key': 'a9f4-f152e97ad808'}, + ), + 'tokens': ['98b37c57-ec62-4e39', '8690ef7d-8004-4916'], + }, + {'SECRET_KEY': 'c4d77c62-6196-4f17-a06b-c462cffae87a'}, + ] + cleansed = [ + { + 'login': 'cooper', + 'password': reporter_filter.cleansed_substitute, + 'apps': ( + {'name': 'app1', 'api_key': reporter_filter.cleansed_substitute}, + {'name': 'app2', 'api_key': reporter_filter.cleansed_substitute}, + ), + 'tokens': reporter_filter.cleansed_substitute, + }, + {'SECRET_KEY': reporter_filter.cleansed_substitute}, + ] + self.assertEqual( + reporter_filter.cleanse_setting('SETTING_NAME', initial), + cleansed, + ) + self.assertEqual( + reporter_filter.cleanse_setting('SETTING_NAME', tuple(initial)), + tuple(cleansed), + ) + def test_request_meta_filtering(self): request = self.rf.get('/', HTTP_SECRET_HEADER='super_secret') reporter_filter = SafeExceptionReporterFilter()
Settings are cleaned insufficiently. Description Posting publicly after checking with the rest of the security team. I just ran into a case where django.views.debug.SafeExceptionReporterFilter.get_safe_settings() would return several un-cleansed values. Looking at cleanse_setting() I realized that we ​only take care of `dict`s but don't take other types of iterables into account but ​return them as-is. Example: In my settings.py I have this: MY_SETTING = { "foo": "value", "secret": "value", "token": "value", "something": [ {"foo": "value"}, {"secret": "value"}, {"token": "value"}, ], "else": [ [ {"foo": "value"}, {"secret": "value"}, {"token": "value"}, ], [ {"foo": "value"}, {"secret": "value"}, {"token": "value"}, ], ] } On Django 3.0 and below: >>> import pprint >>> from django.views.debug import get_safe_settings >>> pprint.pprint(get_safe_settings()["MY_SETTING"]) {'else': [[{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}], [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}]], 'foo': 'value', 'secret': '********************', 'something': [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}], 'token': '********************'} On Django 3.1 and up: >>> from django.views.debug import SafeExceptionReporterFilter >>> import pprint >>> pprint.pprint(SafeExceptionReporterFilter().get_safe_settings()["MY_SETTING"]) {'else': [[{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}], [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}]], 'foo': 'value', 'secret': '********************', 'something': [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}], 'token': '********************'}
Do I need to change both versions? Or just create a single implementation for current master branch?
2020-04-11T01:58:27Z
3.1
["test_cleanse_setting_recurses_in_list_tuples (view_tests.tests.test_debug.ExceptionReporterFilterTests)"]
["test_repr (view_tests.tests.test_debug.CallableSettingWrapperTests)", "test_sensitive_post_parameters_not_called (view_tests.tests.test_debug.DecoratorsTests)", "test_sensitive_variables_not_called (view_tests.tests.test_debug.DecoratorsTests)", "test_cleansed_substitute_override (view_tests.tests.test_debug.CustomExceptionReporterFilterTests)", "test_hidden_settings_override (view_tests.tests.test_debug.CustomExceptionReporterFilterTests)", "test_setting_allows_custom_subclass (view_tests.tests.test_debug.CustomExceptionReporterFilterTests)", "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_custom_exception_reporter_filter (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)", "test_non_html_response_encoding (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)", "test_non_sensitive_request (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)", "test_paranoid_request (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)", "test_sensitive_request (view_tests.tests.test_debug.NonHTMLResponseExceptionReporterFilter)", "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_exception_reporter_from_request (view_tests.tests.test_debug.DebugViewTests)", "test_exception_reporter_from_settings (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_technical_404_converter_raise_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_source_not_match (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_cleanse_setting_basic (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_cleanse_setting_ignore_case (view_tests.tests.test_debug.ExceptionReporterFilterTests)", "test_cleanse_setting_recurses_in_dictionary (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_exception_report_uses_meta_filtering (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_request_meta_filtering (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)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django__django-11039
need to identify issue is with sqlmigrate
0
django/core/management/commands/sqlmigrate.py
django/django
d5276398046ce4a102776a1e67dcac2884d80dfe
diff --git a/django/core/management/commands/sqlmigrate.py b/django/core/management/commands/sqlmigrate.py --- a/django/core/management/commands/sqlmigrate.py +++ b/django/core/management/commands/sqlmigrate.py @@ -55,8 +55,9 @@ def handle(self, *args, **options): migration_name, app_label)) targets = [(app_label, migration.name)] - # Show begin/end around output only for atomic migrations - self.output_transaction = migration.atomic + # Show begin/end around output for atomic migrations, if the database + # supports transactional DDL. + self.output_transaction = migration.atomic and connection.features.can_rollback_ddl # Make a plan that represents just the requested migrations and show SQL # for it
diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -536,7 +536,13 @@ def test_sqlmigrate_forwards(self): index_op_desc_unique_together = output.find('-- alter unique_together') index_tx_end = output.find(connection.ops.end_transaction_sql().lower()) - self.assertGreater(index_tx_start, -1, "Transaction start not found") + if connection.features.can_rollback_ddl: + self.assertGreater(index_tx_start, -1, "Transaction start not found") + self.assertGreater( + index_tx_end, index_op_desc_unique_together, + "Transaction end not found or found before operation description (unique_together)" + ) + self.assertGreater( index_op_desc_author, index_tx_start, "Operation description (author) not found or found before transaction start" @@ -553,10 +559,6 @@ def test_sqlmigrate_forwards(self): index_op_desc_unique_together, index_op_desc_tribble, "Operation description (unique_together) not found or found before operation description (tribble)" ) - self.assertGreater( - index_tx_end, index_op_desc_unique_together, - "Transaction end not found or found before operation description (unique_together)" - ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_sqlmigrate_backwards(self): @@ -577,7 +579,12 @@ def test_sqlmigrate_backwards(self): index_drop_table = output.rfind('drop table') index_tx_end = output.find(connection.ops.end_transaction_sql().lower()) - self.assertGreater(index_tx_start, -1, "Transaction start not found") + if connection.features.can_rollback_ddl: + self.assertGreater(index_tx_start, -1, "Transaction start not found") + self.assertGreater( + index_tx_end, index_op_desc_unique_together, + "Transaction end not found or found before DROP TABLE" + ) self.assertGreater( index_op_desc_unique_together, index_tx_start, "Operation description (unique_together) not found or found before transaction start" @@ -595,10 +602,6 @@ def test_sqlmigrate_backwards(self): index_drop_table, index_op_desc_author, "DROP TABLE not found or found before operation description (author)" ) - self.assertGreater( - index_tx_end, index_op_desc_unique_together, - "Transaction end not found or found before DROP TABLE" - ) # Cleanup by unmigrating everything call_command("migrate", "migrations", "zero", verbosity=0) @@ -616,6 +619,22 @@ def test_sqlmigrate_for_non_atomic_migration(self): self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries) self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries) + @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'}) + def test_sqlmigrate_for_non_transactional_databases(self): + """ + Transaction wrappers aren't shown for databases that don't support + transactional DDL. + """ + out = io.StringIO() + with mock.patch.object(connection.features, 'can_rollback_ddl', False): + call_command('sqlmigrate', 'migrations', '0001', stdout=out) + output = out.getvalue().lower() + queries = [q.strip() for q in output.splitlines()] + start_transaction_sql = connection.ops.start_transaction_sql() + if start_transaction_sql: + self.assertNotIn(start_transaction_sql.lower(), queries) + self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries) + @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.migrated_app",
sqlmigrate wraps it's outpout in BEGIN/COMMIT even if the database doesn't support transactional DDL Description (last modified by Simon Charette) The migration executor only adds the outer BEGIN/COMMIT ​if the migration is atomic and ​the schema editor can rollback DDL but the current sqlmigrate logic only takes migration.atomic into consideration. The issue can be addressed by Changing sqlmigrate ​assignment of self.output_transaction to consider connection.features.can_rollback_ddl as well. Adding a test in tests/migrations/test_commands.py based on ​an existing test for non-atomic migrations that mocks connection.features.can_rollback_ddl to False instead of overdidding MIGRATION_MODULES to point to a non-atomic migration. I marked the ticket as easy picking because I included the above guidelines but feel free to uncheck it if you deem it inappropriate.
I marked the ticket as easy picking because I included the above guidelines but feel free to uncheck it if you deem it inappropriate. Super. We don't have enough Easy Pickings tickets for the demand, so this kind of thing is great. (IMO 🙂) Hey, I'm working on this ticket, I would like you to know as this is my first ticket it may take little longer to complete :). Here is a ​| link to the working branch You may feel free to post references or elaborate more on the topic. Hi Parth. No problem. If you need help please reach out to e.g. ​django-core-mentorship citing this issue, and where you've got to/got stuck. Welcome aboard, and have fun! ✨
2019-03-01T10:24:38Z
3.0
["test_sqlmigrate_for_non_transactional_databases (migrations.test_commands.MigrateTests)"]
["test_makemigrations_app_name_specified_as_label (migrations.test_commands.AppLabelErrorTests)", "test_makemigrations_nonexistent_app_label (migrations.test_commands.AppLabelErrorTests)", "test_migrate_app_name_specified_as_label (migrations.test_commands.AppLabelErrorTests)", "test_migrate_nonexistent_app_label (migrations.test_commands.AppLabelErrorTests)", "test_showmigrations_app_name_specified_as_label (migrations.test_commands.AppLabelErrorTests)", "test_showmigrations_nonexistent_app_label (migrations.test_commands.AppLabelErrorTests)", "test_sqlmigrate_app_name_specified_as_label (migrations.test_commands.AppLabelErrorTests)", "test_sqlmigrate_nonexistent_app_label (migrations.test_commands.AppLabelErrorTests)", "test_squashmigrations_app_name_specified_as_label (migrations.test_commands.AppLabelErrorTests)", "test_squashmigrations_nonexistent_app_label (migrations.test_commands.AppLabelErrorTests)", "--squashed-name specifies the new migration's name.", "--squashed-name also works if a start migration is omitted.", "test_squashmigrations_initial_attribute (migrations.test_commands.SquashMigrationsTests)", "test_squashmigrations_invalid_start (migrations.test_commands.SquashMigrationsTests)", "test_squashmigrations_optimizes (migrations.test_commands.SquashMigrationsTests)", "test_squashmigrations_squashes (migrations.test_commands.SquashMigrationsTests)", "test_squashmigrations_valid_start (migrations.test_commands.SquashMigrationsTests)", "test_ticket_23799_squashmigrations_no_optimize (migrations.test_commands.SquashMigrationsTests)", "test_failing_migration (migrations.test_commands.MakeMigrationsTests)", "test_files_content (migrations.test_commands.MakeMigrationsTests)", "test_makemigration_merge_dry_run (migrations.test_commands.MakeMigrationsTests)", "test_makemigration_merge_dry_run_verbosity_3 (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_auto_now_add_interactive (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_check (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_conflict_exit (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_consistency_checks_respect_routers (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_default_merge_name (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_disabled_migrations_for_app (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_dry_run (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_dry_run_verbosity_3 (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_empty_connections (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_empty_migration (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_empty_no_app_specified (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_handle_merge (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_inconsistent_history (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_interactive_accept (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_interactive_by_default (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_interactive_reject (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_merge_dont_output_dependency_operations (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_merge_no_conflict (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_migration_path_output (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_migration_path_output_valueerror (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_migrations_announce (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_migrations_modules_nonexistent_toplevel_package (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_migrations_modules_path_not_exist (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_no_apps_initial (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_no_changes (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_no_changes_no_apps (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_no_common_ancestor (migrations.test_commands.MakeMigrationsTests)", "Migration directories without an __init__.py file are allowed.", "test_makemigrations_non_interactive_no_field_rename (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_non_interactive_no_model_rename (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_non_interactive_not_null_addition (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_non_interactive_not_null_alteration (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_order (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_unspecified_app_with_conflict_merge (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_unspecified_app_with_conflict_no_merge (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_with_custom_name (migrations.test_commands.MakeMigrationsTests)", "test_makemigrations_with_invalid_custom_name (migrations.test_commands.MakeMigrationsTests)", "test_ambigious_prefix (migrations.test_commands.MigrateTests)", "test_app_without_migrations (migrations.test_commands.MigrateTests)", "test_migrate (migrations.test_commands.MigrateTests)", "test_migrate_conflict_exit (migrations.test_commands.MigrateTests)", "test_migrate_fake_initial (migrations.test_commands.MigrateTests)", "test_migrate_fake_split_initial (migrations.test_commands.MigrateTests)", "test_migrate_inconsistent_history (migrations.test_commands.MigrateTests)", "test_migrate_initial_false (migrations.test_commands.MigrateTests)", "Tests migrate --plan output.", "test_migrate_record_replaced (migrations.test_commands.MigrateTests)", "test_migrate_record_squashed (migrations.test_commands.MigrateTests)", "test_migrate_syncdb_app_label (migrations.test_commands.MigrateTests)", "test_migrate_syncdb_app_with_migrations (migrations.test_commands.MigrateTests)", "test_migrate_syncdb_deferred_sql_executed_with_schemaeditor (migrations.test_commands.MigrateTests)", "test_migrate_with_system_checks (migrations.test_commands.MigrateTests)", "test_regression_22823_unmigrated_fk_to_migrated_model (migrations.test_commands.MigrateTests)", "test_showmigrations_list (migrations.test_commands.MigrateTests)", "test_showmigrations_no_migrations (migrations.test_commands.MigrateTests)", "test_showmigrations_plan (migrations.test_commands.MigrateTests)", "test_showmigrations_plan_app_label_no_migrations (migrations.test_commands.MigrateTests)", "test_showmigrations_plan_multiple_app_labels (migrations.test_commands.MigrateTests)", "test_showmigrations_plan_no_migrations (migrations.test_commands.MigrateTests)", "test_showmigrations_plan_single_app_label (migrations.test_commands.MigrateTests)", "test_showmigrations_plan_squashed (migrations.test_commands.MigrateTests)", "test_showmigrations_unmigrated_app (migrations.test_commands.MigrateTests)", "test_sqlmigrate_backwards (migrations.test_commands.MigrateTests)", "test_sqlmigrate_for_non_atomic_migration (migrations.test_commands.MigrateTests)", "test_sqlmigrate_forwards (migrations.test_commands.MigrateTests)", "test_unknown_prefix (migrations.test_commands.MigrateTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django__django-15498
difficult but docstring is really helpfu to get that
2
django/views/static.py
django/django
d90e34c61b27fba2527834806639eebbcfab9631
diff --git a/django/views/static.py b/django/views/static.py --- a/django/views/static.py +++ b/django/views/static.py @@ -129,12 +129,14 @@ def was_modified_since(header=None, mtime=0, size=0): if header is None: raise ValueError matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, re.IGNORECASE) + if matches is None: + raise ValueError header_mtime = parse_http_date(matches[1]) header_len = matches[3] if header_len and int(header_len) != size: raise ValueError if int(mtime) > header_mtime: raise ValueError - except (AttributeError, ValueError, OverflowError): + except (ValueError, OverflowError): return True return False
diff --git a/tests/view_tests/tests/test_static.py b/tests/view_tests/tests/test_static.py --- a/tests/view_tests/tests/test_static.py +++ b/tests/view_tests/tests/test_static.py @@ -191,3 +191,6 @@ def test_was_modified_since_fp(self): mtime = 1343416141.107817 header = http_date(mtime) self.assertFalse(was_modified_since(header, mtime)) + + def test_was_modified_since_empty_string(self): + self.assertTrue(was_modified_since(header="", mtime=1))
Fix handling empty string for If-Modified-Since header Description Empty string used to be ignored for If-Modified-Since header, but now raises exception since d6aff369ad3. Fix handling empty string for If-Modified-Since header Description Empty string used to be ignored for If-Modified-Since header, but now raises exception since d6aff369ad3.
2022-03-10T19:47:15Z
4.1
["test_was_modified_since_empty_string (view_tests.tests.test_static.StaticUtilsTests)"]
["A floating point mtime does not disturb was_modified_since (#18675).", "test_404 (view_tests.tests.test_static.StaticHelperTest)", "The static view should stream files in chunks to avoid large memory usage", "test_copes_with_empty_path_component (view_tests.tests.test_static.StaticHelperTest)", "No URLs are served if DEBUG=False.", "test_empty_prefix (view_tests.tests.test_static.StaticHelperTest)", "test_index (view_tests.tests.test_static.StaticHelperTest)", "test_index_custom_template (view_tests.tests.test_static.StaticHelperTest)", "test_index_subdir (view_tests.tests.test_static.StaticHelperTest)", "Handle bogus If-Modified-Since values gracefully", "Handle even more bogus If-Modified-Since values gracefully", "test_is_modified_since (view_tests.tests.test_static.StaticHelperTest)", "test_not_modified_since (view_tests.tests.test_static.StaticHelperTest)", "test_prefix (view_tests.tests.test_static.StaticHelperTest)", "The static view can serve static media", "No URLs are served if prefix contains a netloc part.", "test_unknown_mime_type (view_tests.tests.test_static.StaticHelperTest)", "test_404 (view_tests.tests.test_static.StaticTests)", "test_copes_with_empty_path_component (view_tests.tests.test_static.StaticTests)", "test_index (view_tests.tests.test_static.StaticTests)", "test_index_custom_template (view_tests.tests.test_static.StaticTests)", "test_index_subdir (view_tests.tests.test_static.StaticTests)", "test_is_modified_since (view_tests.tests.test_static.StaticTests)", "test_not_modified_since (view_tests.tests.test_static.StaticTests)", "test_unknown_mime_type (view_tests.tests.test_static.StaticTests)"]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django__django-14999
easy after determining root issue as renamemodel
0
django/db/migrations/operations/models.py
django/django
a754b82dac511475b6276039471ccd17cc64aeb8
diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -320,12 +320,13 @@ def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.new_name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.old_name) + old_db_table = old_model._meta.db_table + new_db_table = new_model._meta.db_table + # Don't alter when a table name is not changed. + if old_db_table == new_db_table: + return # Move the main table - schema_editor.alter_db_table( - new_model, - old_model._meta.db_table, - new_model._meta.db_table, - ) + schema_editor.alter_db_table(new_model, old_db_table, new_db_table) # Alter the fields pointing to us for related_object in old_model._meta.related_objects: if related_object.related_model == old_model:
diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -793,6 +793,28 @@ def test_rename_model_with_m2m(self): self.assertEqual(Rider.objects.count(), 2) self.assertEqual(Pony._meta.get_field('riders').remote_field.through.objects.count(), 2) + def test_rename_model_with_db_table_noop(self): + app_label = 'test_rmwdbtn' + project_state = self.apply_operations(app_label, ProjectState(), operations=[ + migrations.CreateModel('Rider', fields=[ + ('id', models.AutoField(primary_key=True)), + ], options={'db_table': 'rider'}), + migrations.CreateModel('Pony', fields=[ + ('id', models.AutoField(primary_key=True)), + ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)), + ]), + ]) + new_state = project_state.clone() + operation = migrations.RenameModel('Rider', 'Runner') + operation.state_forwards(app_label, new_state) + + with connection.schema_editor() as editor: + with self.assertNumQueries(0): + operation.database_forwards(app_label, editor, project_state, new_state) + with connection.schema_editor() as editor: + with self.assertNumQueries(0): + operation.database_backwards(app_label, editor, new_state, project_state) + def test_rename_m2m_target_model(self): app_label = "test_rename_m2m_target_model" project_state = self.apply_operations(app_label, ProjectState(), operations=[
RenameModel with db_table should be a noop. Description A RenameModel operation that already has db_table defined must be a noop. In Postgres, it drops and recreates foreign key constraints. In sqlite it recreates the table (as expected for a table renaming).
2021-10-16T09:31:21Z
4.1
["test_rename_model_with_db_table_noop (migrations.test_operations.OperationTests)"]
["test_references_model_mixin (migrations.test_operations.TestCreateModel)", "test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_name (migrations.test_operations.FieldOperationTests)", "test_references_field_by_remote_field_model (migrations.test_operations.FieldOperationTests)", "test_references_field_by_through (migrations.test_operations.FieldOperationTests)", "test_references_field_by_to_fields (migrations.test_operations.FieldOperationTests)", "test_references_model (migrations.test_operations.FieldOperationTests)", "Tests the AddField operation.", "The CreateTable operation ignores swapped models.", "Tests the DeleteModel operation ignores swapped models.", "Add/RemoveIndex operations ignore swapped models.", "Tests the AddField operation on TextField/BinaryField.", "Tests the AddField operation on TextField.", "test_add_constraint (migrations.test_operations.OperationTests)", "test_add_constraint_combinable (migrations.test_operations.OperationTests)", "test_add_constraint_percent_escaping (migrations.test_operations.OperationTests)", "test_add_covering_unique_constraint (migrations.test_operations.OperationTests)", "test_add_deferred_unique_constraint (migrations.test_operations.OperationTests)", "Tests the AddField operation with a ManyToManyField.", "Tests the AddField operation's state alteration", "test_add_func_index (migrations.test_operations.OperationTests)", "test_add_func_unique_constraint (migrations.test_operations.OperationTests)", "Test the AddIndex operation.", "test_add_index_state_forwards (migrations.test_operations.OperationTests)", "test_add_or_constraint (migrations.test_operations.OperationTests)", "test_add_partial_unique_constraint (migrations.test_operations.OperationTests)", "Tests the AlterField operation.", "AlterField operation is a noop when adding only a db_column and the", "test_alter_field_m2m (migrations.test_operations.OperationTests)", "Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)", "Tests the AlterField operation on primary keys changes any FKs pointing to it.", "test_alter_field_pk_mti_fk (migrations.test_operations.OperationTests)", "If AlterField doesn't reload state appropriately, the second AlterField", "test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_with_func_index (migrations.test_operations.OperationTests)", "test_alter_field_with_func_unique_constraint (migrations.test_operations.OperationTests)", "Test AlterField operation with an index to ensure indexes created via", "Creating and then altering an FK works correctly", "Altering an FK to a non-FK works (#23244)", "Tests the AlterIndexTogether operation.", "test_alter_index_together_remove (migrations.test_operations.OperationTests)", "test_alter_index_together_remove_with_unique_together (migrations.test_operations.OperationTests)", "The managers on a model are set.", "Tests the AlterModelOptions operation.", "The AlterModelOptions operation removes keys from the dict (#23121)", "Tests the AlterModelTable operation.", "AlterModelTable should rename auto-generated M2M tables.", "Tests the AlterModelTable operation if the table name is set to None.", "Tests the AlterModelTable operation if the table name is not changed.", "Tests the AlterOrderWithRespectTo operation.", "Tests the AlterUniqueTogether operation.", "test_alter_unique_together_remove (migrations.test_operations.OperationTests)", "A field may be migrated from AutoField to BigAutoField.", "Column names that are SQL keywords shouldn't cause problems when used", "Tests the CreateModel operation.", "Tests the CreateModel operation on a multi-table inheritance setup.", "Test the creation of a model with a ManyToMany field and the", "test_create_model_with_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_deferred_unique_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_base (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_field_name (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_manager_name (migrations.test_operations.OperationTests)", "test_create_model_with_partial_unique_constraint (migrations.test_operations.OperationTests)", "Tests the CreateModel operation directly followed by an", "CreateModel ignores proxy models.", "CreateModel ignores unmanaged models.", "Tests the DeleteModel operation.", "test_delete_mti_model (migrations.test_operations.OperationTests)", "Tests the DeleteModel operation ignores proxy models.", "A model with BigAutoField can be created.", "test_remove_constraint (migrations.test_operations.OperationTests)", "test_remove_covering_unique_constraint (migrations.test_operations.OperationTests)", "test_remove_deferred_unique_constraint (migrations.test_operations.OperationTests)", "Tests the RemoveField operation.", "test_remove_field_m2m (migrations.test_operations.OperationTests)", "test_remove_field_m2m_with_through (migrations.test_operations.OperationTests)", "Tests the RemoveField operation on a foreign key.", "test_remove_func_index (migrations.test_operations.OperationTests)", "test_remove_func_unique_constraint (migrations.test_operations.OperationTests)", "Test the RemoveIndex operation.", "test_remove_index_state_forwards (migrations.test_operations.OperationTests)", "test_remove_partial_unique_constraint (migrations.test_operations.OperationTests)", "Tests the RenameField operation.", "test_rename_field_case (migrations.test_operations.OperationTests)", "If RenameField doesn't reload state appropriately, the AlterField", "test_rename_field_with_db_column (migrations.test_operations.OperationTests)", "RenameModel renames a many-to-many column after a RenameField.", "test_rename_m2m_target_model (migrations.test_operations.OperationTests)", "test_rename_m2m_through_model (migrations.test_operations.OperationTests)", "test_rename_missing_field (migrations.test_operations.OperationTests)", "Tests the RenameModel operation.", "RenameModel operations shouldn't trigger the caching of rendered apps", "test_rename_model_with_m2m (migrations.test_operations.OperationTests)", "Tests the RenameModel operation on model with self referential FK.", "test_rename_model_with_self_referential_m2m (migrations.test_operations.OperationTests)", "Tests the RenameModel operation on a model which has a superclass that", "test_rename_referenced_field_state_forward (migrations.test_operations.OperationTests)", "test_repoint_field_m2m (migrations.test_operations.OperationTests)", "Tests the RunPython operation", "Tests the RunPython operation correctly handles the \"atomic\" keyword", "#24098 - Tests no-op RunPython operations.", "#24282 - Model changes to a FK reverse side update the model", "Tests the RunSQL operation.", "test_run_sql_add_missing_semicolon_on_collect_sql (migrations.test_operations.OperationTests)", "#24098 - Tests no-op RunSQL operations.", "#23426 - RunSQL should accept parameters.", "#23426 - RunSQL should fail when a list of statements with an incorrect", "Tests the SeparateDatabaseAndState operation.", "A complex SeparateDatabaseAndState operation: Multiple operations both", "A field may be migrated from SmallAutoField to AutoField.", "A field may be migrated from SmallAutoField to BigAutoField."]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django__django-14534
need to identify id_for_label
0
django/forms/boundfield.py
django/django
910ecd1b8df7678f45c3d507dde6bcb1faafa243
diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py --- a/django/forms/boundfield.py +++ b/django/forms/boundfield.py @@ -277,7 +277,7 @@ def template_name(self): @property def id_for_label(self): - return 'id_%s_%s' % (self.data['name'], self.data['index']) + return self.data['attrs'].get('id') @property def choice_label(self):
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -720,7 +720,7 @@ class BeatleForm(Form): fields = list(BeatleForm(auto_id=False)['name']) self.assertEqual(len(fields), 4) - self.assertEqual(fields[0].id_for_label, 'id_name_0') + self.assertEqual(fields[0].id_for_label, None) self.assertEqual(fields[0].choice_label, 'John') self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>') self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>') @@ -3202,6 +3202,22 @@ class SomeForm(Form): self.assertEqual(form['field'].id_for_label, 'myCustomID') self.assertEqual(form['field_none'].id_for_label, 'id_field_none') + def test_boundfield_subwidget_id_for_label(self): + """ + If auto_id is provided when initializing the form, the generated ID in + subwidgets must reflect that prefix. + """ + class SomeForm(Form): + field = MultipleChoiceField( + choices=[('a', 'A'), ('b', 'B')], + widget=CheckboxSelectMultiple, + ) + + form = SomeForm(auto_id='prefix_%s') + subwidgets = form['field'].subwidgets + self.assertEqual(subwidgets[0].id_for_label, 'prefix_field_0') + self.assertEqual(subwidgets[1].id_for_label, 'prefix_field_1') + def test_boundfield_widget_type(self): class SomeForm(Form): first_name = CharField()
BoundWidget.id_for_label ignores id set by ChoiceWidget.options Description If you look at the implementation of BoundField.subwidgets class BoundField: ... def subwidgets(self): id_ = self.field.widget.attrs.get('id') or self.auto_id attrs = {'id': id_} if id_ else {} attrs = self.build_widget_attrs(attrs) return [ BoundWidget(self.field.widget, widget, self.form.renderer) for widget in self.field.widget.subwidgets(self.html_name, self.value(), attrs=attrs) ] one sees that self.field.widget.subwidgets(self.html_name, self.value(), attrs=attrs) returns a dict and assigns it to widget. Now widget['attrs']['id'] contains the "id" we would like to use when rendering the label of our CheckboxSelectMultiple. However BoundWidget.id_for_label() is implemented as class BoundWidget: ... def id_for_label(self): return 'id_%s_%s' % (self.data['name'], self.data['index']) ignoring the id available through self.data['attrs']['id']. This re-implementation for rendering the "id" is confusing and presumably not intended. Nobody has probably realized that so far, because rarely the auto_id-argument is overridden when initializing a form. If however we do, one would assume that the method BoundWidget.id_for_label renders that string as specified through the auto_id format-string. By changing the code from above to class BoundWidget: ... def id_for_label(self): return self.data['attrs']['id'] that function behaves as expected. Please note that this error only occurs when rendering the subwidgets of a widget of type CheckboxSelectMultiple. This has nothing to do with the method BoundField.id_for_label().
Hey Jacob — Sounds right: I didn't look in-depth but, if you can put your example in a test case it will be clear enough in the PR. Thanks. Thanks Carlton, I will create a pull request asap. Here is a pull request fixing this bug: ​https://github.com/django/django/pull/14533 (closed without merging) Here is the new pull request ​https://github.com/django/django/pull/14534 against main The regression test looks good; fails before fix, passes afterward. I don't think this one ​qualifies for a backport, so I'm changing it to "Ready for checkin." Do the commits need to be squashed?
2021-06-17T15:37:34Z
4.0
["If auto_id is provided when initializing the form, the generated ID in", "test_iterable_boundfield_select (forms_tests.tests.test_forms.FormsTestCase)"]
["test_attribute_class (forms_tests.tests.test_forms.RendererTests)", "test_attribute_instance (forms_tests.tests.test_forms.RendererTests)", "test_attribute_override (forms_tests.tests.test_forms.RendererTests)", "test_default (forms_tests.tests.test_forms.RendererTests)", "test_kwarg_class (forms_tests.tests.test_forms.RendererTests)", "test_kwarg_instance (forms_tests.tests.test_forms.RendererTests)", "test_accessing_clean (forms_tests.tests.test_forms.FormsTestCase)", "test_auto_id (forms_tests.tests.test_forms.FormsTestCase)", "test_auto_id_false (forms_tests.tests.test_forms.FormsTestCase)", "test_auto_id_on_form_and_field (forms_tests.tests.test_forms.FormsTestCase)", "test_auto_id_true (forms_tests.tests.test_forms.FormsTestCase)", "BaseForm.__repr__() should contain some basic information about the", "BaseForm.__repr__() shouldn't trigger the form validation.", "test_basic_processing_in_view (forms_tests.tests.test_forms.FormsTestCase)", "BoundField without any choices (subwidgets) evaluates to True.", "test_boundfield_css_classes (forms_tests.tests.test_forms.FormsTestCase)", "test_boundfield_empty_label (forms_tests.tests.test_forms.FormsTestCase)", "test_boundfield_id_for_label (forms_tests.tests.test_forms.FormsTestCase)", "If an id is provided in `Widget.attrs`, it overrides the generated ID,", "Multiple calls to BoundField().value() in an unbound form should return", "test_boundfield_invalid_index (forms_tests.tests.test_forms.FormsTestCase)", "test_boundfield_label_tag (forms_tests.tests.test_forms.FormsTestCase)", "test_boundfield_label_tag_custom_widget_id_for_label (forms_tests.tests.test_forms.FormsTestCase)", "If a widget has no id, label_tag just returns the text with no", "test_boundfield_slice (forms_tests.tests.test_forms.FormsTestCase)", "test_boundfield_value_disabled_callable_initial (forms_tests.tests.test_forms.FormsTestCase)", "test_boundfield_values (forms_tests.tests.test_forms.FormsTestCase)", "test_boundfield_widget_type (forms_tests.tests.test_forms.FormsTestCase)", "test_callable_initial_data (forms_tests.tests.test_forms.FormsTestCase)", "test_changed_data (forms_tests.tests.test_forms.FormsTestCase)", "test_changing_cleaned_data_in_clean (forms_tests.tests.test_forms.FormsTestCase)", "test_changing_cleaned_data_nothing_returned (forms_tests.tests.test_forms.FormsTestCase)", "test_checkbox_auto_id (forms_tests.tests.test_forms.FormsTestCase)", "test_class_prefix (forms_tests.tests.test_forms.FormsTestCase)", "test_cleaned_data_only_fields (forms_tests.tests.test_forms.FormsTestCase)", "test_custom_boundfield (forms_tests.tests.test_forms.FormsTestCase)", "Form fields can customize what is considered as an empty value", "test_datetime_changed_data_callable_with_microseconds (forms_tests.tests.test_forms.FormsTestCase)", "The cleaned value for a form with a disabled DateTimeField and callable", "Cleaning a form with a disabled DateTimeField and callable initial", "test_dynamic_construction (forms_tests.tests.test_forms.FormsTestCase)", "test_dynamic_initial_data (forms_tests.tests.test_forms.FormsTestCase)", "test_empty_data_files_multi_value_dict (forms_tests.tests.test_forms.FormsTestCase)", "test_empty_dict (forms_tests.tests.test_forms.FormsTestCase)", "test_empty_permitted (forms_tests.tests.test_forms.FormsTestCase)", "test_empty_permitted_and_use_required_attribute (forms_tests.tests.test_forms.FormsTestCase)", "test_empty_querydict_args (forms_tests.tests.test_forms.FormsTestCase)", "test_error_dict (forms_tests.tests.test_forms.FormsTestCase)", "#21962 - adding html escape flag to ErrorDict", "test_error_escaping (forms_tests.tests.test_forms.FormsTestCase)", "test_error_html_required_html_classes (forms_tests.tests.test_forms.FormsTestCase)", "test_error_list (forms_tests.tests.test_forms.FormsTestCase)", "test_error_list_class_has_one_class_specified (forms_tests.tests.test_forms.FormsTestCase)", "test_error_list_class_not_specified (forms_tests.tests.test_forms.FormsTestCase)", "test_error_list_with_hidden_field_errors_has_correct_class (forms_tests.tests.test_forms.FormsTestCase)", "test_error_list_with_non_field_errors_has_correct_class (forms_tests.tests.test_forms.FormsTestCase)", "test_errorlist_override (forms_tests.tests.test_forms.FormsTestCase)", "test_escaping (forms_tests.tests.test_forms.FormsTestCase)", "test_explicit_field_order (forms_tests.tests.test_forms.FormsTestCase)", "test_extracting_hidden_and_visible (forms_tests.tests.test_forms.FormsTestCase)", "test_field_deep_copy_error_messages (forms_tests.tests.test_forms.FormsTestCase)", "#5749 - `field_name` may be used as a key in _html_output().", "BaseForm._html_output() should merge all the hidden input fields and", "test_field_named_data (forms_tests.tests.test_forms.FormsTestCase)", "test_field_order (forms_tests.tests.test_forms.FormsTestCase)", "`css_classes` may be used as a key in _html_output() (class comes", "`css_classes` may be used as a key in _html_output() (empty classes).", "test_filefield_initial_callable (forms_tests.tests.test_forms.FormsTestCase)", "test_filefield_with_fileinput_required (forms_tests.tests.test_forms.FormsTestCase)", "test_form (forms_tests.tests.test_forms.FormsTestCase)", "test_form_html_attributes (forms_tests.tests.test_forms.FormsTestCase)", "test_form_with_disabled_fields (forms_tests.tests.test_forms.FormsTestCase)", "test_form_with_iterable_boundfield (forms_tests.tests.test_forms.FormsTestCase)", "test_form_with_iterable_boundfield_id (forms_tests.tests.test_forms.FormsTestCase)", "test_form_with_noniterable_boundfield (forms_tests.tests.test_forms.FormsTestCase)", "test_forms_with_choices (forms_tests.tests.test_forms.FormsTestCase)", "test_forms_with_file_fields (forms_tests.tests.test_forms.FormsTestCase)", "test_forms_with_multiple_choice (forms_tests.tests.test_forms.FormsTestCase)", "test_forms_with_null_boolean (forms_tests.tests.test_forms.FormsTestCase)", "test_forms_with_prefixes (forms_tests.tests.test_forms.FormsTestCase)", "test_forms_with_radio (forms_tests.tests.test_forms.FormsTestCase)", "test_get_initial_for_field (forms_tests.tests.test_forms.FormsTestCase)", "test_has_error (forms_tests.tests.test_forms.FormsTestCase)", "test_help_text (forms_tests.tests.test_forms.FormsTestCase)", "test_hidden_data (forms_tests.tests.test_forms.FormsTestCase)", "test_hidden_initial_gets_id (forms_tests.tests.test_forms.FormsTestCase)", "test_hidden_widget (forms_tests.tests.test_forms.FormsTestCase)", "test_html_output_with_hidden_input_field_errors (forms_tests.tests.test_forms.FormsTestCase)", "test_html_safe (forms_tests.tests.test_forms.FormsTestCase)", "test_id_on_field (forms_tests.tests.test_forms.FormsTestCase)", "test_initial_data (forms_tests.tests.test_forms.FormsTestCase)", "test_initial_datetime_values (forms_tests.tests.test_forms.FormsTestCase)", "#17922 - required_css_class is added to the label_tag() of required fields.", "test_label_split_datetime_not_displayed (forms_tests.tests.test_forms.FormsTestCase)", "test_label_suffix (forms_tests.tests.test_forms.FormsTestCase)", "BoundField label_suffix (if provided) overrides Form label_suffix", "test_multipart_encoded_form (forms_tests.tests.test_forms.FormsTestCase)", "test_multiple_choice_checkbox (forms_tests.tests.test_forms.FormsTestCase)", "test_multiple_choice_list_data (forms_tests.tests.test_forms.FormsTestCase)", "test_multiple_hidden (forms_tests.tests.test_forms.FormsTestCase)", "#19298 -- MultiValueField needs to override the default as it needs", "test_multivalue_field_validation (forms_tests.tests.test_forms.FormsTestCase)", "#23674 -- invalid initial data should not break form.changed_data()", "test_multivalue_optional_subfields (forms_tests.tests.test_forms.FormsTestCase)", "test_only_hidden_fields (forms_tests.tests.test_forms.FormsTestCase)", "test_optional_data (forms_tests.tests.test_forms.FormsTestCase)", "test_specifying_labels (forms_tests.tests.test_forms.FormsTestCase)", "test_subclassing_forms (forms_tests.tests.test_forms.FormsTestCase)", "test_templates_with_forms (forms_tests.tests.test_forms.FormsTestCase)", "test_unbound_form (forms_tests.tests.test_forms.FormsTestCase)", "test_unicode_values (forms_tests.tests.test_forms.FormsTestCase)", "test_update_error_dict (forms_tests.tests.test_forms.FormsTestCase)", "test_use_required_attribute_false (forms_tests.tests.test_forms.FormsTestCase)", "test_use_required_attribute_true (forms_tests.tests.test_forms.FormsTestCase)", "test_validating_multiple_fields (forms_tests.tests.test_forms.FormsTestCase)", "The list of form field validators can be modified without polluting", "test_various_boolean_values (forms_tests.tests.test_forms.FormsTestCase)", "test_widget_output (forms_tests.tests.test_forms.FormsTestCase)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-14238
need to identify bigautofields
0
django/db/models/fields/__init__.py
django/django
30e123ed351317b7527f632b3b7dc4e81e850449
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -2524,7 +2524,7 @@ def __instancecheck__(self, instance): return isinstance(instance, self._subclasses) or super().__instancecheck__(instance) def __subclasscheck__(self, subclass): - return subclass in self._subclasses or super().__subclasscheck__(subclass) + return issubclass(subclass, self._subclasses) or super().__subclasscheck__(subclass) class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):
diff --git a/tests/model_fields/test_autofield.py b/tests/model_fields/test_autofield.py --- a/tests/model_fields/test_autofield.py +++ b/tests/model_fields/test_autofield.py @@ -30,6 +30,18 @@ def test_isinstance_of_autofield(self): self.assertIsInstance(field(), models.AutoField) def test_issubclass_of_autofield(self): - for field in (models.BigAutoField, models.SmallAutoField): + class MyBigAutoField(models.BigAutoField): + pass + + class MySmallAutoField(models.SmallAutoField): + pass + + tests = [ + MyBigAutoField, + MySmallAutoField, + models.BigAutoField, + models.SmallAutoField, + ] + for field in tests: with self.subTest(field.__name__): self.assertTrue(issubclass(field, models.AutoField)) diff --git a/tests/model_options/test_default_pk.py b/tests/model_options/test_default_pk.py --- a/tests/model_options/test_default_pk.py +++ b/tests/model_options/test_default_pk.py @@ -4,6 +4,10 @@ from django.test.utils import isolate_apps +class MyBigAutoField(models.BigAutoField): + pass + + @isolate_apps('model_options') class TestDefaultPK(SimpleTestCase): @override_settings(DEFAULT_AUTO_FIELD='django.db.models.NonexistentAutoField') @@ -74,6 +78,15 @@ class Model(models.Model): self.assertIsInstance(Model._meta.pk, models.SmallAutoField) + @override_settings( + DEFAULT_AUTO_FIELD='model_options.test_default_pk.MyBigAutoField' + ) + def test_default_auto_field_setting_bigautofield_subclass(self): + class Model(models.Model): + pass + + self.assertIsInstance(Model._meta.pk, MyBigAutoField) + @isolate_apps('model_options.apps.ModelPKConfig') @override_settings(DEFAULT_AUTO_FIELD='django.db.models.AutoField') def test_app_default_auto_field(self):
DEFAULT_AUTO_FIELD subclass check fails for subclasses of BigAutoField and SmallAutoField. Description Set DEFAULT_AUTO_FIELD = "example.core.models.MyBigAutoField" , with contents of example.core.models: from django.db import models class MyBigAutoField(models.BigAutoField): pass class MyModel(models.Model): pass Django then crashes with: Traceback (most recent call last): File "/..././manage.py", line 21, in <module> main() File "/..././manage.py", line 17, in main execute_from_command_line(sys.argv) File "/.../venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/.../venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/.../venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/.../venv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/.../venv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/Users/chainz/.pyenv/versions/3.9.1/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/.../example/core/models.py", line 8, in <module> class MyModel(models.Model): File "/.../venv/lib/python3.9/site-packages/django/db/models/base.py", line 320, in __new__ new_class._prepare() File "/.../venv/lib/python3.9/site-packages/django/db/models/base.py", line 333, in _prepare opts._prepare(cls) File "/.../venv/lib/python3.9/site-packages/django/db/models/options.py", line 285, in _prepare pk_class = self._get_default_pk_class() File "/.../venv/lib/python3.9/site-packages/django/db/models/options.py", line 246, in _get_default_pk_class raise ValueError( ValueError: Primary key 'example.core.models.MyBigAutoField' referred by DEFAULT_AUTO_FIELD must subclass AutoField. This can be fixed in AutoFieldMeta.__subclasscheck__ by allowing subclasses of those classes in the _subclasses property.
2021-04-08T10:41:31Z
4.0
["test_issubclass_of_autofield (model_fields.test_autofield.AutoFieldInheritanceTests)", "test_default_auto_field_setting_bigautofield_subclass (model_options.test_default_pk.TestDefaultPK)"]
["test_isinstance_of_autofield (model_fields.test_autofield.AutoFieldInheritanceTests)", "Backend specific ranges can be saved without corruption.", "Backend specific ranges are enforced at the model validation level", "test_coercing (model_fields.test_autofield.AutoFieldTests)", "Values within the documented safe range pass validation, and can be", "test_invalid_value (model_fields.test_autofield.AutoFieldTests)", "If there are stricter validators than the ones from the database", "test_rel_db_type (model_fields.test_autofield.AutoFieldTests)", "test_types (model_fields.test_autofield.AutoFieldTests)", "test_app_default_auto_field (model_options.test_default_pk.TestDefaultPK)", "test_app_default_auto_field_non_auto (model_options.test_default_pk.TestDefaultPK)", "test_app_default_auto_field_none (model_options.test_default_pk.TestDefaultPK)", "test_app_default_auto_field_nonexistent (model_options.test_default_pk.TestDefaultPK)", "test_default_auto_field_setting (model_options.test_default_pk.TestDefaultPK)", "test_default_auto_field_setting_non_auto (model_options.test_default_pk.TestDefaultPK)", "test_default_auto_field_setting_none (model_options.test_default_pk.TestDefaultPK)", "test_default_auto_field_setting_nonexistent (model_options.test_default_pk.TestDefaultPK)", "test_m2m_app_default_auto_field (model_options.test_default_pk.TestDefaultPK)", "test_m2m_default_auto_field_setting (model_options.test_default_pk.TestDefaultPK)", "test_coercing (model_fields.test_integerfield.SmallIntegerFieldTests)", "test_invalid_value (model_fields.test_integerfield.SmallIntegerFieldTests)", "test_rel_db_type (model_fields.test_integerfield.SmallIntegerFieldTests)", "test_types (model_fields.test_integerfield.SmallIntegerFieldTests)", "test_coercing (model_fields.test_integerfield.IntegerFieldTests)", "test_invalid_value (model_fields.test_integerfield.IntegerFieldTests)", "test_rel_db_type (model_fields.test_integerfield.IntegerFieldTests)", "test_types (model_fields.test_integerfield.IntegerFieldTests)", "test_coercing (model_fields.test_integerfield.BigIntegerFieldTests)", "test_invalid_value (model_fields.test_integerfield.BigIntegerFieldTests)", "test_rel_db_type (model_fields.test_integerfield.BigIntegerFieldTests)", "test_types (model_fields.test_integerfield.BigIntegerFieldTests)", "test_coercing (model_fields.test_autofield.SmallAutoFieldTests)", "test_invalid_value (model_fields.test_autofield.SmallAutoFieldTests)", "test_rel_db_type (model_fields.test_autofield.SmallAutoFieldTests)", "test_types (model_fields.test_autofield.SmallAutoFieldTests)", "test_coercing (model_fields.test_autofield.BigAutoFieldTests)", "test_invalid_value (model_fields.test_autofield.BigAutoFieldTests)", "test_rel_db_type (model_fields.test_autofield.BigAutoFieldTests)", "test_types (model_fields.test_autofield.BigAutoFieldTests)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django__django-11742
need to identify Field as the root
0
django/db/models/fields/__init__.py
django/django
fee75d2aed4e58ada6567c464cfd22e89dc65f4a
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -257,6 +257,7 @@ def is_value(value, accept_promise=True): ) ] + choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: @@ -270,16 +271,32 @@ def is_value(value, accept_promise=True): for value, human_name in group_choices ): break + if self.max_length is not None and group_choices: + choice_max_length = max( + choice_max_length, + *(len(value) for value, _ in group_choices if isinstance(value, str)), + ) except (TypeError, ValueError): # No groups, choices in the form [value, display] value, human_name = group_name, group_choices if not is_value(value) or not is_value(human_name): break + if self.max_length is not None and isinstance(value, str): + choice_max_length = max(choice_max_length, len(value)) # Special case: choices=['ab'] if isinstance(choices_group, str): break else: + if self.max_length is not None and choice_max_length > self.max_length: + return [ + checks.Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=self, + id='fields.E009', + ), + ] return [] return [
diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py --- a/tests/invalid_models_tests/test_ordinary_fields.py +++ b/tests/invalid_models_tests/test_ordinary_fields.py @@ -304,6 +304,32 @@ class Model(models.Model): self.assertEqual(Model._meta.get_field('field').check(), []) + def test_choices_in_max_length(self): + class Model(models.Model): + field = models.CharField( + max_length=2, choices=[ + ('ABC', 'Value Too Long!'), ('OK', 'Good') + ], + ) + group = models.CharField( + max_length=2, choices=[ + ('Nested', [('OK', 'Good'), ('Longer', 'Longer')]), + ('Grouped', [('Bad', 'Bad')]), + ], + ) + + for name, choice_max_length in (('field', 3), ('group', 6)): + with self.subTest(name): + field = Model._meta.get_field(name) + self.assertEqual(field.check(), [ + Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=field, + id='fields.E009', + ), + ]) + def test_bad_db_index_value(self): class Model(models.Model): field = models.CharField(max_length=10, db_index='bad')
Add check to ensure max_length fits longest choice. Description There is currently no check to ensure that Field.max_length is large enough to fit the longest value in Field.choices. This would be very helpful as often this mistake is not noticed until an attempt is made to save a record with those values that are too long.
2019-09-04T08:30:14Z
3.0
["test_choices_in_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group (invalid_models_tests.test_ordinary_fields.CharFieldTests)"]
["test_non_nullable_blank (invalid_models_tests.test_ordinary_fields.GenericIPAddressFieldTests)", "test_forbidden_files_and_folders (invalid_models_tests.test_ordinary_fields.FilePathFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.IntegerFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_callable_not_checked (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_starts_with_slash (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_default_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_str_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_valid_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_auto_now_and_auto_now_add_raise_error (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_bad_values_of_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_decimal_places_greater_than_max_digits (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_negative_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_required_attributes (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_bad_db_index_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_validators (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_bad_structure (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_iterable_of_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_lazy_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_missing_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_negative_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_non_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "Two letters isn't a valid choice pair.", "test_str_max_length_type (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_str_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_pillow_installed (invalid_models_tests.test_ordinary_fields.ImageFieldTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27