【问题标题】:How do i replace or overwrite imagges stored in cloudinary using django如何使用 django 替换或覆盖存储在 cloudinary 中的图像
【发布时间】:2022-01-19 19:55:14
【问题描述】:

我想设置用户个人资料图片,但不想在每次更改图片时都添加新文件有没有办法覆盖或替换 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)

如果需要更多代码,请发表评论,我一定会将其编辑到问题中 非常感谢

【问题讨论】:

    标签: python django django-models django-views cloudinary


    【解决方案1】:

    很难看到你在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

    【讨论】:

    • 如何调用公共 ID?
    • AttributeError: 'ForwardOneToOneDescriptor' 对象没有属性 'username' 我收到此错误
    • 如果您认识用户,您应该能够传入该个人资料图片的公共 ID,假设您将其存储在您的数据库中的某处。
    猜你喜欢
    • 2019-01-08
    • 2018-04-11
    • 2014-08-13
    • 2017-01-13
    • 1970-01-01
    • 2015-09-24
    • 2019-09-08
    • 2015-06-14
    • 1970-01-01
    相关资源
    最近更新 更多