Django FileField: 如何只返回文件名(在模板中)

在我的 FileField型模型中有一个字段。这给我一个类型为 File的对象,它具有以下方法:

File.name: 文件的名称,包括 MEDIA_ROOT.

我想要的是类似于“ .filename”的东西,它只能给我文件名,而不是路径,比如:

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

也就是 myfile.jpg

86459 次浏览

In your model definition:

import os


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


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

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

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

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