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

John picture John · Apr 21, 2010 · Viewed 61.2k times · Source

I've got a field in my model of type FileField. This gives me an object of type File, which has the following method:

File.name: The name of the file including the relative path from MEDIA_ROOT.

What I want is something like ".filename" that will only give me the filename and not the path as well, something like:

{% for download in downloads %}
  <div class="download">
    <div class="title">{{download.file.filename}}</div>
  </div>
{% endfor %}

Which would give something like myfile.jpg

Answer

Ludwik Trammer picture Ludwik Trammer · Apr 21, 2010

In your model definition:

import os

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

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