FileField Size and Name in Template
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 = mo开发者_运维知识库dels.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?
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>
精彩评论