Python Django 模板无法从模型函数中获取名称

Python Django Template cannot get name from model function

虽然我知道我可以从我们的模型中调用函数定义,但我似乎无法提取我上传文档的文件名。下面我尝试了以下模板格式,但要么是我想要的输出结果:

.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

<form action="." method="GET">
{% if documents %}
   <ul>
      {% for document in documents %}
        <li> {{ document.filename }}
        <input type = "submit" name="load-data" value="Add to Layer"/>
        </li>
      {% endfor %}
  </ul>

结果:只显示按钮。

.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/filename.csv)和按钮

这是我的其余代码:

models.py

class Document(models.Model):
     docfile = models.FileField(upload_to='document/%Y/%m/%d')

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

views.py

documents = Document.objects.all()
return render(request, 'gridlock/upload-data.html',
              {
               'documents' : documents,
               'form': form
              })

我希望有人能解释为什么我尝试了一切: {{ document.docfile.filename }}{{document.file.filename}}{{document.filename}} 对我都不起作用?谢谢!

我认为您与 {{ document.filename }} 非常接近,除了您的模型需要更改

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

进入

def filename(self):
    # try printing the filename here to see if it works
    print (os.path.basename(self.docfile.name))
    return os.path.basename(self.docfile.name)

在您的模型中,该字段称为 docfile,因此您需要使用 self.docfile 来获取其值。

来源:django filefield return filename only in template