如何使用Django的filesizeformat

bea*_*tty 3 python django

我有一个小应用程序,我正在努力使用Django内置的filesizeformat.目前,格式如下:{{ value|filesizeformat }}.我知道我需要在我的view.py文件中定义它,但是,我似乎无法弄清楚如何做到这一点.我试过使用下面的语法:

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 
Run Code Online (Sandbox Code Playgroud)

然后我在模板中用'bytes'替换'value'但是,这似乎不起作用.有什么建议?

Eli*_*sky 9

filesizeformat是一个内置的 过滤器,您不需要自己实现它.您应该将值提供给模板,例如:

{% for page in pages %}
    <li>page.name {{page.size|filesizeformat}}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

现在,当您从视图中呈现模板时,提供一个pages参数,该参数是一个dicts列表,如:

[{'name': 'page1', 'size': 10000}, {'name': 'page2', 'size': 5023034}]
Run Code Online (Sandbox Code Playgroud)

等等.