Django: How to display only a filename in your template


This is for situations you want to display only a filename without the entire path in your template. This solution is portable, allowing you to apply it to several apps within your project.

1. Create a directory in your project and name it “templatetags”:

myproject 
 - templatetags

2. In the templatetags folder create a blank “__init__.py” file so Django can treat the directory as a python package

myproject
 - templatetags
   - __init__.py

2. Create another file in the templatetags folder and name it “filename”
so now the directory structure should look like this:

myproject
 - templatetags
   - __init__.py
   - filename.py

3. Add below codes to the filename.py:

#filename.py
import os
from django import template

register = template.Library()

@register.filter
def getfilename(value):
    return os.path.basename(value.file.name)

4. Now add below codes to your template to retrieve a filename from a file field:

{% load filename %}


{{submission.file | getfilename }}


About Matthias 33 Articles
I am a Software Engineer from Houston, TX who love to write codes that brings great ideas to live. In my professional life, I have created software for different industries including Oil & Gas, Finance, Service Provider, Cloud Computing and Embedded Systems. When not writting codes, i enjoy travelling, good music and photography. You can reach me at me@matthiasomisore.com.

1 Trackback / Pingback

  1. [Djagno] ファイルアップロード機能の使い方 [基本設定編] | IT技術情報局

Leave a Reply

Your email address will not be published.


*