如何使用django替换或覆盖存储在cloudinary中的图像



我想设置用户配置文件图片,但不想每次更改图片时都添加新文件。有没有办法覆盖或替换cloudinary数据库中的图像以下是型号:

class CloudinaryField(BaseCloudinaryField):
def upload_options(self, model_instance):
return {
'public_id': UserProfile.user.username,
'filename': "Hey",
'unique_filename': False,
'overwrite': False,
'resource_type': 'image',
'tags': ['Profile'],
'invalidate': True,
'quality': 'auto:eco',
}

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
Nick_Name = models.CharField(default="Hey", max_length=250)
Profile_pic = CloudinaryField('Profile_Pic', default="")

表单:

class UserProfilePage(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['Nick_Name', 'Profile_pic']
help_texts = {
'Nick_Name': 'This will act as your display name',
}
Profile_pic = CloudinaryFileField(
options={
'folder': 'Profile/',
})

最后是观点:

def edit(request):
func = data(request)
form = UserEdit(initial={'email': request.user.email})
profile = UserProfilePage(initial={'Nick_Name': request.user.userprofile.Nick_Name,
'Profile_pic': request.user.userprofile.Profile_pic.url})
if request.method == "POST":
form = UserEdit(data=request.POST or None, instance=request.user)
profile = UserProfilePage(data=request.POST or None, instance=request.user.userprofile, files=request.FILES)
if form.is_valid() and profile.is_valid():
user = form.save()
profiles = profile.save()
return redirect("Profile_Page")
ctx = {
'form': form,
'profile': profile,
'url': func[0],
'name': func[1],
'date': func[2],
}
return render(request, "Edit_User.html", ctx)

如果需要更多的代码,请评论,我一定会把它编辑成问题非常感谢

很难看到在Profile_pic中为类UserProfilePage传递了什么。但在选项下,您应该传入上传参数:

'public_id': UserProfile.user.username,
'overwrite': True,
'resource_type': 'image',
'invalidate': True,

这应该用该公共id覆盖资产,并在CDN级别使其无效。Cloudinary文档中对此进行了介绍:https://cloudinary.com/documentation/django_image_and_video_upload#django_forms_and_models

最新更新