虽然我知道我可以从模型中调用函数定义,但我似乎无法提取上传文档的文件名。下面,我尝试了以下模板格式,但其中任何一种都来自我所需的输出:
.html版本1
<form action="." method="GET">
{% if documents %}
<ul>
{% for document in documents %}
<li> {{ document.docfile.filename }}
<input type = "submit" name="load-data" value="Add to Layer"/>
</li>
{% endfor %}
</ul>
结果:只显示按钮。
.html版本2
^{pr2}$结果:只显示按钮。
.html版本3
<form action="." method="GET">
{% if documents %}
<ul>
{% for document in documents %}
<li> {{ document.docfile.name }}
<input type = "submit" name="load-data" value="Add to Layer"/>
</li>
{% endfor %}
</ul>
结果:打印完整的路径名(例如:/documents/2016/10/08/文件名.csv)连同按钮
下面是我剩下的代码:
模型.py
class Document(models.Model):
docfile = models.FileField(upload_to='document/%Y/%m/%d')
def filename(self):
return os.path.basename(self.file.name)
视图.py
documents = Document.objects.all()
return render(request, 'gridlock/upload-data.html',
{
'documents' : documents,
'form': form
})
我希望有人能解释我为什么要这么做:
{{ document.docfile.filename }}
或{{document.file.filename}}
或{
我想你已经很接近
{{ document.filename }}
,除了你的模型你需要改变进入
^{pr2}$在您的模型中,该字段称为docfile,因此您需要使用self.doc文件为了得到它的价值。在
来源:django filefield return filename only in template
相关问题 更多 >
编程相关推荐