Hello Awesome People!
我的问题很简单,因为标题清楚地描述了它。
我在某些模型中有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上迁移我的所有文件时,它会引发错误,例如我没有权限这样做。
我想知道错误是什么或者是否有另一种方法来测试文件是否存在?
提前谢谢!
答案 0 :(得分:3)
您应该使用与存储无关的Storage.exists()
方法。
存储对象应该在FieldFile
本身可用,所以类似
return self.file.storage.exists(self.file.name)
应该这样做。
答案 1 :(得分:0)
在 Django 3+ 中:
model.file_field.field.storage.exists(model.file_field.name)
答案 2 :(得分:-1)
这可能也有效。尝试打开<Stage width={500} height={500} scaleY={-1} offsetY={500}>
并返回file
,如果发生异常,请返回True
。
False