views:

249

answers:

2

I've got a field in my model of type FileField. This gives me an object of type 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

thanks

+1  A: 

In your model definition:

import os.path

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

    def filename(self):
        return os.path.basename(self.file.name)
Ludwik Trammer
worked great but needed the param to be passed into basename as self.file.name. I think it needs this as self.file is a file object rather than the string to the file.
John
Thanks. I updated the post.
Ludwik Trammer
A: 

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