Solve retrieve file name Django fileField with file.name that show full path


When working with Django FileField, you usually need to retrieve filename with file.name. But, when you make query file.name, instead you got full path of filename. This is annoying, right?

We can use templatetags to get basename of file.name by :

1. Create folder templatetags that contains __init__.py and filename.py

1
2
3
4
5
APPS
  |
  |__ templatetags
            |___ __init__.py
            |___ filename.py


Eg:

1
2
3
4
5
6
7
8
import os

class YourModels(models.Model):
    ….

    def save(self, *args, **kwargs):
            self.file.name = os.path.basename(self.file.name)
            return super(YourModels, self).save(*args, **kwargs)

Now, when you query

1
file.name

You got only the filename instead of full path.
To get the full-path, just query :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os

from django import template

register = template.Library()


@register.filter
def filename(value):
    """Get basename of full-path. Return error if file not found."""
    if os.path.isfile(value):
        return os.path.basename(value)
    else:
        return ‘No File’

On your templates :

1
2
{% load filename %}
{{ data.file.name|filename }}

It will show ‘No file’ if the file is not exists.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.