FileField大小和模板中的名称

sil*_*zzo 12 django django-templates django-file-upload

如何在模板中获取FileField的大小和名称?

我的模型设置如下:

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

我的模板设置如下:

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

如何显示文件名和大小?

Dom*_*ger 34

一旦你有权访问a的值FileField,你就得到了一个type值File,它有以下几种方法:

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

File.size 文件的大小(以字节为单位).

所以你可以在你的模板中做到这一点:

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

为了得到更多的人类可读的文件大小(对于你的用户谁还会通过看64.5 MB为67633152个字节混淆-我称他们wusses),那么你可能会感兴趣的filesizeformat过滤器,用于车削大小以字节为单位进之类的东西 13 KB,4.1 MB,102 bytes等,您在模板中使用,如下所示:

<div class="size">{{download.file.size|filesizeformat}}</div>
Run Code Online (Sandbox Code Playgroud)