模板中的文件字段大小和名称

发布于 2024-08-18 08:12:00 字数 576 浏览 1 评论 0原文

如何获取模板中 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不吻晚风 2024-08-25 08:12:00

一旦您可以访问 FileField,您有一个 File,它具有以下方法:

文件.name
文件名,包括 MEDIA_ROOT 的相对路径。

文件大小
文件的大小(以字节为单位)。

因此,您可以在模板中执行此操作:

{% 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 %}

为了获得更易于理解的文件大小(对于那些将 64.5 MB 视为 67633152 字节而感到困惑的用户 - 我称它们为 wusses),那么您可能会对 filesizeformat 过滤器,用于将大小转换为字节转换为 13 KB4.1 MB102 bytes 等,您可以在模板中使用这些内容,如下所示:

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文