Simple file size from bytes to kb/mb/gb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django import template

register = template.Library()

def sizify(value):
    """
    Simple kb/mb/gb size snippet for templates:
    
    {{ product.file.size|sizify }}
    """
    #value = ing(value)
    if value < 512000:
        value = value / 1024.0
        ext = 'kb'
    elif value < 4194304000:
        value = value / 1048576.0
        ext = 'mb'
    else:
        value = value / 1073741824.0
        ext = 'gb'
    return '%s %s' % (str(round(value, 2)), ext)

register.filter('sizify', sizify)

More like this

  1. ByteSplitterField by Lacour 1 year, 9 months ago
  2. Image model with thumbnail by clawlor 2 years, 10 months ago
  3. Template tag to create a list from one or more variables and/or literals by davidchambers 2 years, 8 months ago
  4. Random-image template tag by pbx 6 years, 1 month ago
  5. Render arbitrary models - template tag by jeffschenck 3 years, 7 months ago

Comments

btubbs (on January 14, 2010):

Is this an improvement over http://docs.djangoproject.com/en/dev/ref/templates/builtins/#filesizeformat ?

#

pimpim (on January 15, 2010):

Like btubbs said, take a look at [http://code.djangoproject.com/svn/django/trunk/django/template/defaultfilters.py] for filesizeformat..

It's also better to keep 'bytes' for values < 1024.

#

bryanhelmig (on January 19, 2010):

Ah, well, I had no clue there already existed a tag for this. And so many more! Well, that settles that. Thanks btubbs.

#

(Forgotten your password?)