From 047d161164b2459434e6a17891f079f5f80d4cef Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Sat, 14 Aug 2010 12:45:15 +0000 Subject: [PATCH] Fixed #14002 -- Updated filesize filter to support terabyte and petabyte file sizes. Thanks to Aaron T. Myers for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@13584 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- AUTHORS | 1 + django/template/defaultfilters.py | 18 ++++++++++++------ tests/regressiontests/defaultfilters/tests.py | 9 +++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/AUTHORS b/AUTHORS index 7324a699a5..2d7ad725c8 100644 --- a/AUTHORS +++ b/AUTHORS @@ -344,6 +344,7 @@ answer newbie questions, and generally made Django that much better: James Murty msundstr Robert Myers + Aaron T. Myers Alexander Myodov Nebojša Dorđević Doug Napoleone diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 1e58ff71ca..1a9f834b03 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -807,13 +807,19 @@ def filesizeformat(bytes): except (TypeError,ValueError,UnicodeDecodeError): return u"0 bytes" - if bytes < 1024: + BYTE_UNITS = ( + ('KB', 1024), + ('MB', 1024 * 1024), + ('GB', 1024 * 1024 * 1024), + ('TB', 1024 * 1024 * 1024 * 1024), + ('PB', 1024 * 1024 * 1024 * 1024 * 1024) + ) + + if bytes < BYTE_UNITS[0][1]: return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} - if bytes < 1024 * 1024: - return ugettext("%.1f KB") % (bytes / 1024) - if bytes < 1024 * 1024 * 1024: - return ugettext("%.1f MB") % (bytes / (1024 * 1024)) - return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024)) + for index, (unit, unit_size) in enumerate(BYTE_UNITS): + if bytes < unit_size * 1024 or index == len(BYTE_UNITS) - 1: + return ugettext("%.1f %s") % (bytes / unit_size, unit) filesizeformat.is_safe = True def pluralize(value, arg=u's'): diff --git a/tests/regressiontests/defaultfilters/tests.py b/tests/regressiontests/defaultfilters/tests.py index 25555081e4..8341f83e36 100644 --- a/tests/regressiontests/defaultfilters/tests.py +++ b/tests/regressiontests/defaultfilters/tests.py @@ -476,6 +476,15 @@ u'1024.0 MB' >>> filesizeformat(1024*1024*1024) u'1.0 GB' +>>> filesizeformat(1024*1024*1024*1024) +u'1.0 TB' + +>>> filesizeformat(1024*1024*1024*1024*1024) +u'1.0 PB' + +>>> filesizeformat(1024*1024*1024*1024*1024*2000) +u'2000.0 PB' + >>> filesizeformat(complex(1,-1)) u'0 bytes'