Nips
Nips

Reputation: 13870

How to get file size in template?

I have model with CharField:

absolute_path_to_file = models.CharField(max_length=255)

And I want to display in template size of this file. How to do it? Filter?

{{ object.absolute_path_to_file|<????>size</????> }}

Upvotes: 1

Views: 6502

Answers (3)

Jose Luis de la Rosa
Jose Luis de la Rosa

Reputation: 716

This is a way using the "custom filter" way:

import os
from django import template

register = template.Library()

@register.filter
def filesize(value):
    """Returns the filesize of the filename given in value"""
    return os.path.getsize(value)

That code should be in your django app in the folder "templatetags", for example in a python module named "utils.py". Then, to use the filter in a template this is an example:

{% load utils %}
{{ object.absolute_path_to_file|filesize }}

as well, you can anidate filters like this:

{{ object.absolute_path_to_file|filesize|filesizeformat }}

Upvotes: 9

Some programmer dude
Some programmer dude

Reputation: 409216

If you can't use FileField, then you can create a custom filter that takes the argument and tries to get the file size of that using the standard Python os.path module.

Upvotes: 1

JamesO
JamesO

Reputation: 25946

Use FileField instead, then you can do

{{ object.absolute_path_to_file.size }}

Upvotes: 5

Related Questions