我有这个型号:
def generate_filename(self, filename):
url = "files/users/%s/%s" % (self.user.id, filename)
return url
class Upload(models.Model):
user = modelo.ForeignKey(User, null=True)
docfile = modelo.FileField(upload_to=generate_filename)
Views.py
allfiles = Upload.objects.all()
我在django中有一个上传文件列表:
<ul>
{% for item in allfiles %}
<li><a href="{{ item.docfile.url }}">{{ item.docfile.name }}</a></li>
{% endfor %}
</ul>
它在html上显示我文件的完整路径:
files/users/1/test.txt
我只想展示test.txt
我试过这个:
<ul>
{% for item in arquivos %}
<li><a href="{{ item.docfile.url }}">{{ item.docfile.name.split('/')[3] }}</a></a></li>
{% endfor %}
</ul>
但我得到了Could not parse the remainder: '('/')' from 'item.docfile.name.split('/')[3]'
修改
我尝试在myapp/templatetags/filename.py
中创建一个文件:
import os
from django import template
register = template.Library()
@register.filter
def filename(value):
return os.path.basename(value.docfile.name)
在模板中:
{% load filename %}
<ul>
{% for item in allfiles %}
<li><a href="{{ item.docfile.url }}">{{ item.docfile|filename }}</a></li>
{% endfor %}
</ul>
现在我明白了:
'filename' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_static
admin_urls
cache
filaname
future
i18n
l10n
log
static
staticfiles
tz
答案 0 :(得分:0)
对我来说,我希望你在你的模型中创建一个能够为你做这个的功能
import os
class Upload(models.Model):
user = modelo.ForeignKey(User, null=True)
docfile = modelo.FileField(upload_to=generate_filename)
def get_docfile_name(self):
if not self.docfile:
return ""
file_path = self.docfile.name
return os.path.basename(file_path)
模板中的
<ul>
{% for item in allfiles %}
<li><a href="{{ item.docfile.url }}">{{ item.get_docfile_name }}</a></li>
{% endfor %}