Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = 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?

like image 591
silent1mezzo Avatar asked Jan 17 '10 21:01

silent1mezzo


People also ask

How do I limit upload size in Django?

Inside of this file, we specify the function validate_file_size that passes in the parameter, value. size is a built-in attribute of a Django FieldField that allows us to get the size of a file. The size obtained is in bytes. So we want to limit the file upload size is 10MB.

How can I get image name in Django?

You can obtain such name with os. path. splitext [Python-doc] to split a filename in the "root" and the "extension".

What is FileField in Django?

FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput.

How do I store images in Django?

In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory. The list_display list tells Django admin to display its contents in the admin dashboard.


1 Answers

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>
like image 61
Dominic Rodger Avatar answered Oct 19 '22 22:10

Dominic Rodger