小编bea*_*tty的帖子

如何使用Django的filesizeformat

我有一个小应用程序,我正在努力使用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") …
Run Code Online (Sandbox Code Playgroud)

python django

3
推荐指数
1
解决办法
3970
查看次数

标签 统计

django ×1

python ×1