Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Django's filesizeformat

Tags:

python

django

I have a small app I'm working on where I'm trying to use Django's built in filesizeformat. Currently, the format looks like this: {{ value|filesizeformat }}. I understand I need to define this in my view.py file but, I can't seem to figure out how to do that. I've tried to use 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 

I've then replaced 'value' with 'bytes' in the template but, this does not seem to work. Any suggestions?

like image 766
beamupscotty Avatar asked Apr 04 '10 13:04

beamupscotty


People also ask

What does the built in Django template tag Lorem do?

lorem. Displays random “lorem ipsum” Latin text. This is useful for providing sample data in templates. A number (or variable) containing the number of paragraphs or words to generate (default is 1).

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

What is Autoescape in Django?

Definition and Usage The autoescape tag is used to specify if autoescape is on or off. If autoescape is on, which is default, HTML code in variables will be escaped.

What does the built in Django template filter safe do?

This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn't introduce any possibility of unsafe HTML.”


1 Answers

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

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

Now when you render the template from the view provide a pages argument which is a list of dicts like:

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

And so on.

like image 102
Eli Bendersky Avatar answered Sep 28 '22 23:09

Eli Bendersky