我创建了这个函数,将图像从一个 django 模型复制到另一个 django 模型。图片必须冗余保存:
def __copy_file__(from_object,to_object,field):
attr = field.attname
try:
newpath = getattr(from_object,attr).path
dot_at = newpath.rfind(".")
while os.path.exists(newpath):
newpath = newpath[:dot_at] + "_" + newpath[dot_at:]
shutil.copyfile(getattr(from_object,attr).path, newpath)
getattr(to_object,attr).save(newpath, File(open(getattr(from_object,attr).path)))
return True
except ValueError:
return False
但是这个函数会以某种方式创建无效文件..我记得有一天它起作用了,但我今天测试了它但它不再起作用了..
编辑:现在我知道该函数会生成两个图像。一种有效,另一种无效。 shutil.copyfile (etc) 行生成工作文件,并在赋值 getattr(to_object,attr).save (etc) 中再次保存图像。所以这就是问题所在。它应该只是分配,而不是再次复制..
有人能帮帮我吗? :)
请您参考如下方法:
我这样做的方式,假设 from_model 和 to_model 是为带有图像 ImageField 的模型实例:
def copy_image(from_model, to_model):
to_model.image.save(from_model.image.url.split('/')[-1],from_model.image.file,save=True)
