Question

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</????> }}
Was it helpful?

Solution

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 }}

OTHER TIPS

Use FileField instead, then you can do

{{ object.absolute_path_to_file.size }}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top