Django FileField: how to return only the file name (in the template)

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

File.name : file name, including the relative path from MEDIA_ROOT .

I want something like " .filename " that will give me only the file name, not the path, something like:

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

To give something like myfile.jpg

+53
django django-templates django-file-upload
Apr 21 '10 at 2:09 p.m.
source share
3 answers

In the model definition:

 import os class File(models.Model): file = models.FileField() ... def filename(self): return os.path.basename(self.file.name) 
+119
Apr 21 '10 at 14:31
source share

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 %} 
+44
Oct 28 '10 at 19:29
source share

You can access the file name from the file field object with its name.

 class CsvJob(Models.model): file = models.FileField() 

then you can get the file name with specific objects.

 obj = CsvJob.objects.get() obj.file.name property 
0
Sep 16 '16 at 9:00
source share



All Articles