像这样的问题,我有一个包含表单的页面
file = forms.FileFIeld(widget = forms.FIleInput())
但这使我能够浏览客户端计算机上的文件。我想显示我的服务器端文件。我完全意识到安全风险。这是我的个人项目,不会被其他人使用(以防有人对我大喊大叫)。它不必是完全相同的机制。我只想从表单中获取这个名称。不应上传或下载任何内容。
这将作为另一个服务器应用程序的文件选择工具。
如果无法浏览整个计算机,我如何指定可以存储文件以供进一步浏览的目录?
您可以通过您的模型浏览存储的文件。
假设您的模型声明如下
import os
class Document(models.Model):
name = models.CharField(max_length=64)
doc_file = models.FileField(upload_to='documents')
您可以像获取其他字段一样获取该文件
names = []
# To browse your saved file, get the containing models
documents = Document.objects.all()
for doc in documents:
# This is how you get the URL of the file field
url = doc.doc_file.url
# If you need the path of the stored file (in the server)
doc_path = doc.doc_file.path
# get name and size of the file
name, size = doc.doc_file.name.split(os.path.sep)[-1], doc.doc_file.size
names.append(name)
#process your file names
...
然后你只需要处理这个URL,例如将它显示给你的用户。