Skip to content

Instantly share code, notes, and snippets.

@thanos
Created July 11, 2012 15:55
Show Gist options
  • Select an option

  • Save thanos/3091327 to your computer and use it in GitHub Desktop.

Select an option

Save thanos/3091327 to your computer and use it in GitHub Desktop.
Django quantity format template tag/filter
@register.filter(name='quantityformat')
def quantityformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13K, 4.1M,
102, etc).
"""
try:
bytes = float(bytes)
except (TypeError,ValueError,UnicodeDecodeError):
return ungettext("%(size)d", "%(size)d", 0) % {'size': 0}
filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)
if bytes < 1024:
return ungettext("%(size)d", "%(size)d", bytes) % {'size': bytes}
if bytes < 1024 * 1024:
return ugettext("%sK") % filesize_number_format(bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return ugettext("%sM") % filesize_number_format(bytes / (1024 * 1024))
if bytes < 1024 * 1024 * 1024 * 1024:
return ugettext("%sG") % filesize_number_format(bytes / (1024 * 1024 * 1024))
if bytes < 1024 * 1024 * 1024 * 1024 * 1024:
return ugettext("%sT") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024))
return ugettext("%sP") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024))
quantityformat.is_safe = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment