我正在尝试使用Django中的 filestorage 。一切都运行正常,但我的保存方法中的一件事我猜。我有一个FileField
download_url = models.FileField(verbose_name = 'Konfig', upload_to = file_path, storage = OverwriteStorage())
在我的模型中的这个方法中,我创建了file_path
def file_path(instance, filename):
path = os.getcwd() + '/files'
return os.path.join(path, str(instance.download_url), filename)
我使用的文件存储方法是在我的 storage.py 中外包的,我在models.py中导入
from django.core.files.storage import FileSystemStorage
class OverwriteStorage(FileSystemStorage):
def _save(self, name, content):
if self.exists(name):
self.delete(name)
return super(OverwriteStorage, self)._save(name, content)
def get_available_name(self, name):
return name
现在,当我在django的admin界面中创建一个新文件时,它成功上传文件,使用正确的文件路径创建数据库条目,但无法创建正确的路径。当我的文件名是 foo 时,路径将如下所示:
CWD /文件/富/富
如果它的名称是 bar.txt ,它将如下所示:
CWD /文件/跳回到bar.txt /跳回到bar.txt
我不希望django根据文件名创建子目录。你能帮助我吗?
答案 0 :(得分:1)
我很确定你必须重命名保存功能" save"到" _save"。
在Super Call上,您使用了._save,它与上面的保存功能功能不同。
您可以阅读很多关于超级here
的信息