From d4dd3e503c88db92f254769a64b2fcd4c572c7dc Mon Sep 17 00:00:00 2001 From: mriduldhall Date: Fri, 25 Jul 2025 16:27:20 +0100 Subject: [PATCH] Fixed #36519 -- Made center template filter consistent for even/odd padding. Refactored `center` template filter to match f-string behaviour, producing consistent padding for both odd and even fillings. Thanks Lily Acorn for the report and Natalia Bidart for the review. Co-authored-by: Lily Acorn --- AUTHORS | 1 + django/template/defaultfilters.py | 5 ++++- tests/template_tests/filter_tests/test_center.py | 6 ++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 996928f444..2b1c185e36 100644 --- a/AUTHORS +++ b/AUTHORS @@ -764,6 +764,7 @@ answer newbie questions, and generally made Django that much better: Morgan Aubert Moritz Sichert Morten Bagai + Mridul Dhall msaelices msundstr Mushtaq Ali diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index b50b790fc1..3ed9856c08 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -432,7 +432,10 @@ def rjust(value, arg): @stringfilter def center(value, arg): """Center the value in a field of a given width.""" - return value.center(int(arg)) + width = int(arg) + if width <= 0: + return value + return f"{value:^{width}}" @register.filter diff --git a/tests/template_tests/filter_tests/test_center.py b/tests/template_tests/filter_tests/test_center.py index 8d0bf38006..dbbde4f300 100644 --- a/tests/template_tests/filter_tests/test_center.py +++ b/tests/template_tests/filter_tests/test_center.py @@ -35,6 +35,12 @@ class FunctionTests(SimpleTestCase): def test_non_string_input(self): self.assertEqual(center(123, 5), " 123 ") + def test_odd_input(self): + self.assertEqual(center("odd", 6), " odd ") + + def test_even_input(self): + self.assertEqual(center("even", 7), " even ") + def test_widths(self): value = "something" for i in range(-1, len(value) + 1):