From e64d42e753e5c7763398d018f5ccaa95efc7588e Mon Sep 17 00:00:00 2001 From: Tim Richardson Date: Tue, 23 Apr 2024 15:31:59 +1000 Subject: [PATCH] Fixed #35395 -- slice filter crashes on an empty dict with Python 3.12. Keep consistent behaviour of slice() filter between python 3.12 and prior versions in the case of a dict passed to the filter (catch the new to python 3.12 KeyError exception). --- django/template/defaultfilters.py | 2 +- tests/template_tests/filter_tests/test_slice.py | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index a08ce2710dc..02cac06bcfd 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -644,7 +644,7 @@ def slice_filter(value, arg): bits.append(int(x)) return value[slice(*bits)] - except (ValueError, TypeError): + except (ValueError, TypeError, KeyError): return value # Fail silently. diff --git a/tests/template_tests/filter_tests/test_slice.py b/tests/template_tests/filter_tests/test_slice.py index 5a5dd6b1550..23257b1282b 100644 --- a/tests/template_tests/filter_tests/test_slice.py +++ b/tests/template_tests/filter_tests/test_slice.py @@ -53,3 +53,6 @@ class FunctionTests(SimpleTestCase): def test_fail_silently(self): obj = object() self.assertEqual(slice_filter(obj, "0::2"), obj) + + def test_empty_dict(self): + self.assertEqual(slice_filter({}, "1"), {})