Get the file size of the uploaded file in Django app
Asked Answered
P

3

9

I would like show in the template the size of a file that the user have uploaded. I've see that the file object has the attribute size but, because I'm newbie with Python and the development field, I've been trouble to understand how I can use it.

After some test I've developed this script(filesize) to add at the end of the model with which you can upload the file:

class FileUpload(models.Model):
    name = models.CharField(
        max_length=50,
        )
    description = models.TextField(
        max_length=200,
        blank=True,
        )
    file = models.FileField(
        upload_to='blog/%Y/%m/%d'
        )

    def __str__(self):
        return self.name

    @property
    def filesize(self):
        x = self.file.size
        y = 512000
        if x < y:
            value = round(x/1000, 2)
            ext = ' kb'
        elif x < y*1000:
            value = round(x/1000000, 2)
            ext = ' Mb'
        else:
            value = round(x/1000000000, 2)
            ext = ' Gb'
        return str(value)+ext

Is simple now to call the size of the file.

enter image description here

I share this because I hope that is usefull for someone. What I ask is this: there is a better solution?

Paule answered 21/6, 2019 at 7:31 Comment(0)
N
8

You can solve this by using this custom template tag: https://djangosnippets.org/snippets/1866/

Use it then like this in your template:

{% load sizify  %}

{{ yourFile.size|sizify }}

The file size will then be shown in a human readable format (kb, Mb, Gb)

Nevil answered 21/6, 2019 at 8:34 Comment(0)
U
4

You can use the os module of python to get the size of the uploaded file like os.path.getsize('Your file path')

Uncover answered 21/6, 2019 at 7:48 Comment(1)
It is possible to show the size based on kb, Mb, Gb?Paule
C
2

I needed something like this and have already started creating a custom template tag. But then after some more googling, I found out that django has builtins - {{ value|filesizeformat }}

More info here: https://docs.djangoproject.com/en/4.2/ref/templates/builtins/#filesizeformat

Coacervate answered 2/5, 2023 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.