How to use Django filesizeformat

I have a small application that I am working on, where I am trying to use Django built into filesizeformat. Currently, the format is as follows: {{ value|filesizeformat }}. I understand that I need to define this in my view.py file, but I cannot figure out how to do this. I tried using the syntax below:

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 

Then I replaced the “value” with “bytes” in the template, but it doesn't seem to work. Any suggestions?

+3
source share
1 answer

filesizeformat- This is a built-in filter , you do not need to implement it yourself. You must specify a value in the template, for example:

{% for page in pages %}
    <li>page.name {{page.size|filesizeformat}}</li>
{% endfor %}

, , pages, dicts, :

[{'name': 'page1', 'size': 10000}, {'name': 'page2', 'size': 5023034}]

.

+9

Source: https://habr.com/ru/post/1739759/


All Articles