3
我有一个小应用程序,我正在尝试使用Django内置的filesizeformat。目前,格式如下所示:{{ value|filesizeformat }}
。我知道我需要在我的view.py文件中定义这个,但是,我似乎无法弄清楚如何做到这一点。我试着用下面的语法:如何使用Django的文件格式
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
我然后在模板取代“价值”与“字节”,但是,这似乎并没有工作。有什么建议么?
Eli, 感谢您的信息。非常感激。为我工作就像一个魅力。 – beamupscotty 2010-04-05 11:39:38