Home > database >  default image being reuploaded when new account created
default image being reuploaded when new account created

Time:03-01

On my profile model I have a default image. However I would expect that all accounts that have the default image would be reading the same image, but when a new account is created the default.jpg is being re uploaded to the s3 bucket.

The issue is being caused by a compression function if i remove it and the on save code the issue goes away.

how can i not have it re save default.jpg

def compress(image):
                im = Image.open(image)
                out_put_size = (300,300)
                im.thumbnail(out_put_size)
                # create a BytesIO object
                im_io = BytesIO() 
                # save image to BytesIO object
                im = im.resize([500,500])
                #resize image
                im = im.convert("RGB")
                im = im.save(im_io,'JPEG', quality=75) 
                # create a django-friendly Files object
                new_image = File(im_io, name=image.name)
                return new_image

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, max_length=30)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        initial = self._state.adding
        #image compression start
        if self.image and initial:
            # call the compress function
            new_image = compress(self.image)
            # set self.image to new_image
            self.image = new_image
        #image compression end 
        super(Profile,self).save(*args, **kwargs)

CodePudding user response:

Thanks for opening a new question. self.image is always going to evaluate as True because you've set a default image. With a default, it's never null. Hence the compression function is called.

You need to check whether the name attribute of the instance's avatar is different than the default. You can get the field with get_field() meta option and find the the default field value with get_default().

So the full value to compare the instance's image name against would be Profile._meta.get_field('avatar').get_default().

You can break this up into multiple variables for readability or substitute Profile with self.__class__.

def save(self, *args, **kwargs):
    initial = self._state.adding
    avatar_field = Profile._meta.get_field('avatar')
    default_image_name = avatar_field.get_default()
    no_default_image = self.avatar.name != default_image_name
    #image compression start
    if no_default_image and initial:
        # call the compress function
        new_image = compress(self.image)
        # set self.image to new_image
        self.image = new_image
    #image compression end 
    super(Profile,self).save(*args, **kwargs)
  • Related