Home > other >  Reset Avatar ImageField to Default when User Clear Avatar Through DRF or Django Admin
Reset Avatar ImageField to Default when User Clear Avatar Through DRF or Django Admin

Time:12-22

I have django model ImageField called avatar. I want to enable user clear their avatar, so Blank = True. The problem is when user clear their avatar, the ImageField path is now empty. What i want is, the ImageField back to default.

models.py

class Profile(models.Model):
    AVATAR_UPLOAD_TO = "account_avatar/"
    DEFAULT_AVATAR = "default.jpg"

    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    avatar = sorl.thumbnail.ImageField(upload_to=AVATAR_UPLOAD_TO, default=AVATAR_UPLOAD_TO DEFAULT_AVATAR, blank=True, null=True)

I see some related questions Django ImageField overwrites existing path when empty. But the behaviour is not exactly what i want. This answer required the user to upload new avatar, so user couldn't clear their avatar. Another related questions Django - How to reset model fields to their default value?. But i can't implement the save() method on my models

I have tried to implement save() method on Profile model, but it don't work as expected

def save(self, *args, **kwargs):
    if not self.avatar.name:
        setattr(self, 'avatar.name', self.avatar.field.default)

    super().save(*args, **kwargs)  # Call the "real" save() method.

I am new to Django and Django Rest Framework. Please help me, i stuck with this problem from a few days ago. Could you please help with my problems. Thanks in advance!

CodePudding user response:

You were just missing minor code here is how you can proceed in save() method

class Profile(models.Model):
    AVATAR_UPLOAD_TO = "account_avatar/"
    DEFAULT_AVATAR = "default.jpg"

    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    avatar = sorl.thumbnail.ImageField(upload_to=AVATAR_UPLOAD_TO, 
    default=AVATAR_UPLOAD_TO DEFAULT_AVATAR, blank=True, null=True)

    def save(self, *args, **kwargs):
        if not self.avatar:
            self.avatar = self.AVATAR_UPLOAD_TO   self.DEFAULT_AVATAR
        super(Profile,self).save(*args, **kwargs)  # Call the "real" save() method.
  • Related