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.
I share this because I hope that is usefull for someone. What I ask is this: there is a better solution?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With