模板中的文件字段大小和名称
如何获取模板中 FileField 的大小和名称?
我的模型设置如下:
class PDFUpload(models.Model):
user = models.ForeignKey(User, editable=False)
desc = models.CharField(max_length=255)
file = models.FileField(upload_to=upload_pdf)
我的模板设置如下:
{% 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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一旦您可以访问
FileField
,您有一个File
,它具有以下方法:文件.name
:文件名,包括 MEDIA_ROOT 的相对路径。
文件大小
文件的大小(以字节为单位)。
因此,您可以在模板中执行此操作:
为了获得更易于理解的文件大小(对于那些将 64.5 MB 视为 67633152 字节而感到困惑的用户 - 我称它们为 wusses),那么您可能会对
filesizeformat
过滤器,用于将大小转换为字节转换为13 KB
、4.1 MB
、102 bytes
等,您可以在模板中使用这些内容,如下所示:Once you've got access to the value of a
FileField
, you've got a value of typeFile
, 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:
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 like13 KB
,4.1 MB
,102 bytes
, etc, which you use in your template like this: