[Fixed]-FileField Size and Name in Template

50👍

Once you’ve got access to the value of a FileField, you’ve got a value of type File, which has the following methods:

File.name:
The name of file including the relative path from MEDIA_ROOT.

File.size
The size of the file in bytes.

So you can do this in your template:

{% for download in downloads %}
    <div class="download">
        <div class="title">{{download.file.name}}</div>
        <div class="size">{{download.file.size}} bytes</div>
        <div class="desc">{{download.desc}}</div>
    </div>
{% endfor %}

To get a more human-readable filesize (for those of your users who would be confused by seeing 64.5 MB as 67633152 bytes – I call them wusses), then you might be interested in the filesizeformat filter, for turning sizes in bytes into things like 13 KB, 4.1 MB, 102 bytes, etc, which you use in your template like this:

<div class="size">{{download.file.size|filesizeformat}}</div>

Leave a comment