Skip to content

Commit 047d161

Browse files
committed
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
1 parent 4835d86 commit 047d161

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,7 @@ answer newbie questions, and generally made Django that much better:
344344
James Murty
345345
msundstr
346346
Robert Myers <[email protected]>
347+
Aaron T. Myers <[email protected]>
347348
Alexander Myodov <[email protected]>
348349
Nebojša Dorđević
349350
Doug Napoleone <[email protected]>

django/template/defaultfilters.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -807,13 +807,19 @@ def filesizeformat(bytes):
807807
except (TypeError,ValueError,UnicodeDecodeError):
808808
return u"0 bytes"
809809

810-
if bytes < 1024:
810+
BYTE_UNITS = (
811+
('KB', 1024),
812+
('MB', 1024 * 1024),
813+
('GB', 1024 * 1024 * 1024),
814+
('TB', 1024 * 1024 * 1024 * 1024),
815+
('PB', 1024 * 1024 * 1024 * 1024 * 1024)
816+
)
817+
818+
if bytes < BYTE_UNITS[0][1]:
811819
return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
812-
if bytes < 1024 * 1024:
813-
return ugettext("%.1f KB") % (bytes / 1024)
814-
if bytes < 1024 * 1024 * 1024:
815-
return ugettext("%.1f MB") % (bytes / (1024 * 1024))
816-
return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
820+
for index, (unit, unit_size) in enumerate(BYTE_UNITS):
821+
if bytes < unit_size * 1024 or index == len(BYTE_UNITS) - 1:
822+
return ugettext("%.1f %s") % (bytes / unit_size, unit)
817823
filesizeformat.is_safe = True
818824

819825
def pluralize(value, arg=u's'):

tests/regressiontests/defaultfilters/tests.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,15 @@
476476
>>> filesizeformat(1024*1024*1024)
477477
u'1.0 GB'
478478
479+
>>> filesizeformat(1024*1024*1024*1024)
480+
u'1.0 TB'
481+
482+
>>> filesizeformat(1024*1024*1024*1024*1024)
483+
u'1.0 PB'
484+
485+
>>> filesizeformat(1024*1024*1024*1024*1024*2000)
486+
u'2000.0 PB'
487+
479488
>>> filesizeformat(complex(1,-1))
480489
u'0 bytes'
481490

0 commit comments

Comments
 (0)