diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 8319c66eee..5564ee6fcc 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -858,6 +858,10 @@ def filesizeformat(bytes): TB = 1 << 40 PB = 1 << 50 + negative = bytes < 0 + if negative: + bytes = -bytes # Allow formatting of negative numbers. + if bytes < KB: value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} elif bytes < MB: @@ -871,6 +875,8 @@ def filesizeformat(bytes): else: value = ugettext("%s PB") % filesize_number_format(bytes / PB) + if negative: + value = "-%s" % value return avoid_wrapping(value) diff --git a/tests/template_tests/filter_tests/test_filesizeformat.py b/tests/template_tests/filter_tests/test_filesizeformat.py index c94da8c8d6..9d143ca100 100644 --- a/tests/template_tests/filter_tests/test_filesizeformat.py +++ b/tests/template_tests/filter_tests/test_filesizeformat.py @@ -39,3 +39,7 @@ class FunctionTests(SimpleTestCase): self.assertEqual(filesizeformat(complex(1, -1)), '0\xa0Bytes') self.assertEqual(filesizeformat(""), '0\xa0Bytes') self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), '0\xa0Bytes') + + def test_negative_numbers(self): + self.assertEqual(filesizeformat(-100), '-100\xa0bytes') + self.assertEqual(filesizeformat(-1024 * 1024 * 50), '-50.0\xa0MB')