How can I give the image file a random nane when using ProcessedImageField?

139 views
Skip to first unread message

Mike Walker

unread,
Sep 7, 2020, 5:07:38 PM9/7/20
to Django users
I posted this over in the django-imagekit group before I noticed that I am unlikely to get any response over there due to activity level. So I am now over here to ask this goup.

I am using ProcessedImageField to resize images on upload in my user Profile model. The resizing part is working great and the resized image is successfully saved to my s3 bucket.

However what I would like to add is the ability to give the file a random name before upload. This would hopefully avoid the file name collisions issue. I am not sure how approach this yet, could someone point me in the right direction here?

I have included the code for my current model below.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = ProcessedImageField(default='default.jpg', upload_to='profile_pics',
                                processors=[ResizeToFill(200, 200)],
                                format='JPEG', options={'quality': 60})

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

Mike Walker

unread,
Sep 7, 2020, 5:51:06 PM9/7/20
to Django users
Figures, I solved the problem after posting the question. With a bit more searching and reading I found a rather simple solution to this.

Changing the upload_to= to use a callable works. The callable needs to have two parameters instance and filename. changing the file name using a uuid seems to do the trick for now. I have included my solution just incase anyone else wants to do the same thing. :)

def generate_random_name(instance, filename):
    filename = f'{uuid4().hex}.jpg'
    return os.path.join('profile_pics', filename)


Reply all
Reply to author
Forward
0 new messages