如何在其他模型django中保存图像副本?

时间:2019-12-16 09:24:03

标签: django django-models

我正在尝试使用以下代码从AddToHomeScreen对象创建一个Collections对象:-

            namer=get_object_or_404(Collection,CollectionName=collectionview)
            if AddToHomeScreen.objects.filter(Profile=request.user.profile,name=namer.CollectionName,url="Collection").exists():
                obje=AddToHomeScreen.objects.get(Profile=request.user.profile,name=namer.CollectionName,url="Collection")
                obje.delete()
                return JsonResponse({'info':'Deleted'})
            else:

                objec= AddToHomeScreen(Profile=request.user.profile,name=namer.CollectionName,url="Collection",profilepic=namer.ProfilePic)
                objec.save()
                print(objec.profilepic)
                return JsonResponse({'info':'Added'})   

但是此代码中存在一个问题:-假设如果用户删除AddToHomScreen对象,则ProfilePic的{​​{1}}属性也会被删除,因为它们都共享相同的文件。 为了创建图像的副本,我修改了Collection模型的AddToHomeScreen方法:-

save

但是会产生以下错误: from django.core.files.base import ContentFile def save(self): ima=Image.open(self.profilepic) name=self.profilepic.name.split("/")[-1] content=ContentFile(self.profilepic.read()) self.profilepic.save(name,content) super(AddToHomeScreen,self).save() 我该如何实现?

0 个答案:

没有答案