Advertisement
Guest User

humanize_bytes as filter in template of django

a guest
Jan 29th, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. template:
  2. {% load humanize %}
  3. ...
  4. {% if el.filesize %}
  5.     <a href="/get_file/{{el.filename}}">скачать ({{el.filesize|humanize_bytes:0}})</a>
  6. {% else %}
  7.     (0 байт)
  8. {% endif %}
  9.  
  10. templatetags/humanize.py:
  11. from django import template
  12.  
  13. register = template.Library()
  14.  
  15. @register.filter(name='humanize_bytes')
  16. def humanize_bytes(bytes, precision=1):
  17.     abbrevs = (
  18.         (1 << 40L, 'ТБ'),
  19.         (1 << 30L, 'ГБ'),
  20.         (1 << 20L, 'МБ'),
  21.         (1 << 10L, 'КБ'),
  22.         (1, 'Б')
  23.     )
  24.     if bytes == 0:
  25.         return '0 Б'
  26.     if bytes == 1:
  27.         return '1 Б'
  28.     for factor, suffix in abbrevs:
  29.         if bytes >= factor:
  30.             break
  31.     if precision:
  32.         return '%.*f %s' % (precision, bytes / factor, suffix)
  33.     return '%d %s' % (int(bytes / factor), suffix)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement