簡體   English   中英

如何將化身用戶與cloudinary / Django相關聯?

[英]How to associate an avatar a user with cloudinary / Django?

我正在嘗試在Django項目上配置cloudinary。

當前配置調整用戶頭像的大小並將其托管在cloudinary服務器上。

我想將頭像的公鑰與用戶的ID相關聯,以便當用戶希望更改其頭像時,舊的頭像將被新的頭像覆蓋。

我還希望當用戶刪除其帳戶時,關聯的頭像要么刪除雲服務器

我不知道將公鑰與用戶標識符和良好實踐相關聯的想法,還是還有另一種方法?

這是我暫時嘗試做的事情:

表格


class ProfileUpdateForm(forms.ModelForm):
   image = forms.ImageField(label='', required=True, widget=forms.FileInput)
   class Meta:
       model = Profile
       fields = ['image']

views.py

@login_required
def account_edit(request):
   p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)

   if request.method == "POST":
       if p_form.is_valid():
           p_form.save()
           messages.success(request, _(f"Your image has been successfully uploaded!"))
           return redirect('account_edit')
       else:
           messages.error(request, _(f"Image files only"))
           return redirect('account_edit')
   else:
       p_form = ProfileUpdateForm(instance=request.user.profile)


models.py

from cloudinary.models import CloudinaryField


class Profile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)

   image = CloudinaryField("avatar",
       folder = "avatar/",
       public_id = request.user.pk, # NameError: name 'request' is not defined
       notification_url = "https://dashboard.heroku.com/apps/register-start/avatar",
       resource_type = "image",
       transformation=[
                       {'width': 150, 'height': 150, 'gravity': "center", 'crop': "thumb"},
                       ])

如果希望用戶在任何給定時間(例如GitHub)僅擁有一張個人資料圖片,而不是多個(例如Facebook),則可以將圖像的public_idUser的主鍵關聯。

否則,您可以使用隨機生成的public_id(這是不傳遞public_id參數時的默認值),並使用相關的User主鍵標記圖像。

當該人刪除其帳戶時,您需要使用Upload API的destroy方法在Cloudinary中刪除圖像:

cloudinary.uploader.destroy(public_id, **options)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM