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

DjangoDjango TemplatesDjango File-Upload

Django Problem Overview


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

Django Solutions


Solution 1 - Django

In your model definition:

import os

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

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

Solution 2 - Django

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 %}

Solution 3 - Django

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 %}

Solution 4 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - DjangoLudwik TrammerView Answer on Stackoverflow
Solution 2 - Djangorz.View Answer on Stackoverflow
Solution 3 - DjangoOlaleye AbiolaView Answer on Stackoverflow
Solution 4 - DjangoDeadDjangoDjokerView Answer on Stackoverflow