我正在尝试使用以下代码从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()
我该如何实现?