Dataset Viewer
Auto-converted to Parquet Duplicate
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) [email protected]('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 = '[email protected]' 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': '[email protected] (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
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
10