Django FileField: How to return filename only (in template)
You could also use 'cut' in your template
{% for download in downloads %}
<div class="download">
<div class="title">{{download.file.filename|cut:'remove/trailing/dirs/'}}</div>
</div>
{% endfor %}
You can do this by creating a template filter:
In myapp/templatetags/filename.py
:
import os
from django import template
register = template.Library()
@register.filter
def filename(value):
return os.path.basename(value.file.name)
And then in your template:
{% load filename %}
{# ... #}
{% for download in downloads %}
<div class="download">
<div class="title">{{download.file|filename}}</div>
</div>
{% endfor %}
In your model definition:
import os
class File(models.Model):
file = models.FileField()
...
def filename(self):
return os.path.basename(self.file.name)