17

How do I get the size and name of a FileField in a template?

My model is setup like this:

class PDFUpload(models.Model):
    user = models.ForeignKey(User, editable=False)
    desc = models.CharField(max_length=255)
    file = models.FileField(upload_to=upload_pdf)

My template is setup like this:

{% for download in downloads %}
    <div class="download">
        <div class="title"> Name</div>
        <div class="size">64.5 MB</div>
        <div class="desc">{{download.desc}}</div>
    </div>
{% endfor %}

How can I display the file name and size?

silent1mezzo
  • 2,814
  • 4
  • 26
  • 46

1 Answers1

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>
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
  • +1, but would you care to expand on "Once you've got access to the value of a `FileField`, you've got a value of type `File`"? When working with an instance of `FileField` as above (with `download.file`) how do you magically find yourself with an instance of `File` instead? I see quite a lot of this kind of stuff with Django. It can be confusing. And if you could point to any documentation for this, it would be helpful. Thanks. – Faheem Mitha Apr 05 '11 at 10:36
  • Possibly this link [Django Model field reference:Field types](http://docs.djangoproject.com/en/1.2/ref/models/fields/#field-types), which says "When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file." is relevant. I still think it is magical though. – Faheem Mitha Apr 05 '11 at 10:41