如何确保文件存在于Django项目中? [英] How to ensure file exists in Django project?
本文介绍了如何确保文件存在于Django项目中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好!
我的问题很简单,因为标题清楚地描述了它.
My question is simple as the title clearly describes it.
我在某些模型中具有FileField
,我添加了一个属性方法来检查文件的存在:
I have FileField
in some models , I added a property method to check the existance of file:
@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上迁移所有文件时,会引发错误,表明我没有这样做的权限.
This works perfectly in development, but when I migrate all my files on AWS, it raises an Error such I don't have permission to do that.
我想知道是什么问题,还是有另一种方法来测试文件是否存在?
I wonder what's wrong or Is there another way to test whether a file exists?
提前谢谢!
推荐答案
You should use the storage-agnostic Storage.exists()
method.
存储对象应该在FieldFile
本身上可用,所以类似
The storage object should be available on the FieldFile
itself, so something like
return self.file.storage.exists(self.file.name)
应该可以解决问题.
这篇关于如何确保文件存在于Django项目中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文