Home > Mobile >  Rename and resize django images on save
Rename and resize django images on save

Time:12-29

I'm currently trying to resize and rename my images on save

The problem is that I would like to resize my images in order to make them square without stretching the images, and then change the name of the image to a random number.

Currently I'm doing that inside my model :

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(null=True, blank=True)
    image = models.ImageField(default='/profile_pics/default.jpg',
                              null=True,
                              blank=True,
                              upload_to='profile_pics')

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

    def save(self, **kwargs):
        super().save()
        new_name = random.randint(1, 236325984)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (200, 200)
            img.thumbnail(output_size)

        if img.height < 299 or img.width < 299:
            output_size = (200, 200)
            img.thumbnail(output_size)

        img.save(self.image.path)

I also tried to put in my save function os.rename to rename :

new_name = random.randint(1, 236325984)
        name = f'{new_name}.{img.format.lower()}'
        os.rename(self.image.path, os.path.join(os.path.dirname(self.image.path), name))

But that's not working and giving me an error : [WinError 32]

CodePudding user response:

import os
from uuid import uuid4

def path_and_rename(path):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper

and add it to image field

image = models.ImageField(upload_to=path_and_rename('upload/here/'), ...)
  • Related