Django – Image gets uploaded after every save()

I have a custom upload path for any users avatar. I call a function to set the upload path to "avatar/" + str(self.username) + "/" + filename. My problem is everytime the user change e.g. email and save changes, the avatar gets saved again with the same upload path. models.py

def _upload_path(instance, filename):
    return instance.get_upload_path(filename)


def reduce_image_size(avatar):
    img = Image.open(avatar).convert('RGB')
    thumb_io = BytesIO()
    img.save(thumb_io, 'jpeg', quality=50)
    new_image = File(thumb_io, name=avatar.name)
    return new_image


class User(AbstractUser):
    avatar = models.ImageField(upload_to=_upload_path, blank=True, null=True)

    def get_upload_path(self, filename):
        return "avatar/" + str(self.username) + "/" + filename

    def save(self, *args, **kwargs):
        new_image = reduce_image_size(self.avatar)
        self.avatar = new_image

When first upload image the url is /media/avatar/username/the_uploaded_image.jpg and after updating any value it changes to /media/avatar/username/avatar/username/the_uploaded_image.jpg

I tried to check if a path already exsist but it wasnt working.

    if self.avatar and not os.path.exists(settings.MEDIA_URL + self.get_upload_path(self.avatar.name)):
        new_image = reduce_image_size(self.avatar)
        self.avatar = new_image

Do I miss something?

Answer

Change

if self.avatar and not os.path.exists(settings.MEDIA_URL + self.get_upload_path(self.avatar.name)):

to

if not self.pk:

it checks if primary key exsits and should solve your problem