How to use Django's filesizeformat

Posted by Scott LaPlant on Stack Overflow See other posts from Stack Overflow or by Scott LaPlant
Published on 2010-04-04T13:40:59Z Indexed on 2010/04/04 13:43 UTC
Read the original article Hit count: 403

Filed under:
|

I have a small app I'm working on where I'm trying to use Django's built in filesizeformat. Currently, the format looks like this: {{ value|filesizeformat }} I understand I need to define this in my view.py file but, I can't seem to figure out how to do that. I've tried to use the syntax below:

def filesizeformat(bytes): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(bytes) except (TypeError,ValueError,UnicodeDecodeError): return u"0 bytes"

if bytes < 1024:
    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))

filesizeformat.is_safe = True

I've then replaced 'value' with 'bytes' in the template but, this does not seem to work. Any suggestions?

© Stack Overflow or respective owner

Related posts about django

Related posts about python