Joh*_*ohn 55 django django-templates django-file-upload
我在我的FileField类型的模型中有一个字段.这给了我一个类型为File的对象,它有以下方法:
File.name:文件名,包括MEDIA_ROOT的相对路径.
我想要的是类似.filename的东西,它只会给我文件名,而不是路径
就像是:
{% for download in downloads %}
<div class="download">
<div class="title">{{download.file.filename}}</div>
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
这将给出类似myfile.jpg的东西
谢谢
Lud*_*mer 125
在您的模型定义中:
import os
class File(models.Model):
file = models.FileField()
...
def filename(self):
return os.path.basename(self.file.name)
Run Code Online (Sandbox Code Playgroud)
rz.*_*rz. 45
您可以通过创建模板过滤器来完成此操作:
在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)
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中:
{% load filename %}
{# ... #}
{% for download in downloads %}
<div class="download">
<div class="title">{{download.file|filename}}</div>
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
49283 次 |
最近记录: |