Vincent's Site

Renaming file uploads in Django

Date: 2024-12-13
Category: Tutorial
Tags: django, tips

By default, when you add an ImageField to a Django model, it will use the filename of the original file. This isn't ideal for applications where users can upload their own images. We can solve this by passing a function to the upload_to argument. The following code allows you to replace the supplied name with a randomly generated string.

import os
from uuid import uuid4
from django.utils.deconstruct import deconstructible

@deconstructible
class PathAndRename(object):

    def __init__(self, sub_path):
        self.path = sub_path

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

# Then in your model
class Image(models.Model):
    #... other fields
    path_and_rename = PathAndRename('uploads/images/')
    image = models.ImageField(upload_to=path_and_rename)

Previous post Next post