8

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?

MaxDragonheart
  • 1,117
  • 13
  • 34

3 Answers3

7

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)

hendrikschneider
  • 1,696
  • 1
  • 14
  • 26
3

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

0

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