[Django]-Django FileField: How to return filename only (in template)

227👍

In your model definition:

import os

class File(models.Model):
    file = models.FileField()
    ...

    def filename(self):
        return os.path.basename(self.file.name)

60👍

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 %}
👤rz.

3👍

You could also use the cut filter in your template

{% for download in downloads %}
  <div class="download">
    <div class="title">{{download.file.filename|cut:'remove/trailing/dirs/'}}</div>
  </div>
{% endfor %}

-3👍

You can access the filename from the file field object with the name property.

class CsvJob(Models.model):

    file = models.FileField()

then you can get the particular objects filename using.

obj = CsvJob.objects.get()
obj.file.name property

Leave a comment