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:
我的FileField类型模型中有一个字段。这给了我一个类型类型文件的对象,它有以下方法:
File.name: The name of the file including the relative path from MEDIA_ROOT.
文件名:文件的名称,包括来自MEDIA_ROOT的相对路径。
What I want is something like .filename that will only give me the filename and not the path as well
我想要的是像.filename这样的东西,它只给我文件名,而不是路径
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
哪个会给出类似myfile.jpg的东西
thanks
谢谢
3 个解决方案
#1
100
In your model definition:
在您的模型中定义:
import os
class File(models.Model):
file = models.FileField()
...
def filename(self):
return os.path.basename(self.file.name)
#2
35
You can do this by creating a template filter:
您可以通过创建模板过滤器来实现这一点:
In myapp/templatetags/filename.py
:
在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 %}
#3
0
You can access the filename from the file field object with the name property.
您可以使用name属性从file field对象访问文件名。
class CsvJob(Models.model):
file = models.FileField()
then you can get the particular objects filename using.
然后您可以使用特定的对象文件名。
obj = CsvJob.objects.get()
obj.file.name property
#1
100
In your model definition:
在您的模型中定义:
import os
class File(models.Model):
file = models.FileField()
...
def filename(self):
return os.path.basename(self.file.name)
#2
35
You can do this by creating a template filter:
您可以通过创建模板过滤器来实现这一点:
In myapp/templatetags/filename.py
:
在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 %}
#3
0
You can access the filename from the file field object with the name property.
您可以使用name属性从file field对象访问文件名。
class CsvJob(Models.model):
file = models.FileField()
then you can get the particular objects filename using.
然后您可以使用特定的对象文件名。
obj = CsvJob.objects.get()
obj.file.name property