Why function try to processing not downloaded image?

The question arose, why does the function not allow the image to load, but trying to process it at the time of object creation? and how to fix it I would like to know.

def image_as_base64(image_file, format='jpg'):
   
    if not os.path.isfile(image_file):
         return None
    
    encoded_string = ''
    with open(image_file, 'rb') as img_f:
        encoded_string = base64.b64encode(img_f.read()).decode('utf-8')
    return 'data:image/%s;base64,%s' % (format, encoded_string)



# Example Usage



class Post(models.Model):

    cover = models.ImageField()
    base_64 = models.TextField('base_64', blank=True, null=True)
    base_64_large = UnlimitedCharField(blank=True, null=True)
    
    
    def save(self, *args, **kwargs):
        print(image_as_base64(os.path.join(settings.MEDIA_ROOT , self.cover.path)))
        self.base_64 = image_as_base64(os.path.join(settings.MEDIA_ROOT , self.cover.path))
        self.base_64_large = image_as_base64(os.path.join(settings.MEDIA_ROOT , self.cover.path))
        super(Post, self).save(*args, **kwargs)

And if I comment

if not os.path.isfile(image_file):
         return None

I take an Exception Type: FileNotFoundError. If image exist in folder, function works correctly

Back to Top