gpt4 book ai didi

python - 如何确保文件存在于 Django 项目中?

转载 作者:行者123 更新时间:2023-11-28 21:36:44 24 4
gpt4 key购买 nike

你好很棒的人!

我的问题很简单,因为标题清楚地描述了它。

我有 FileField在某些模型中,我添加了一个属性方法来检查文件的存在:

@property
def file_exists(self):
# Because sometimes, the field may contain the string path
# but the file doesn't exist at all in the server
if file: # if the string path exists
return os.path.exists(self.file.path) # If the file exists in server

这在开发中非常有效,但是当我在 AWS 上迁移我的所有文件时,它会引发一个错误,例如我无权这样做。

我想知道出了什么问题,或者有没有其他方法可以测试文件是否存在?

先感谢您!

最佳答案

您应该使用与存储无关的 Storage.exists() 方法。

存储对象应该在 FieldFile 上可用本身,所以像

return self.file.storage.exists(self.file.name)

应该做的伎俩。

关于python - 如何确保文件存在于 Django 项目中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50606068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com