Search code examples
pythondjangodjango-admindjango-models

Change filename before save file in Django


I have the next code to rename my files when upload in django admin (in models.py)

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('directory/', filename)

class Archivo(models.Model):
    archivo = models.FileField(upload_to = get_file_path)

That works for me, but i want to pass the directory dynamically, something like this:

def get_file_path(instance, filename, directory_string_var):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join(directory_string_var, filename)

If i do that, i can't pass the directory parameter (variable) to the method in upload_to option of the "archivo" field.


Solution

  • If your goal is just preventing the files to fill up the given directory (this is a concern because depending on the filesystem, some operations over a directory with too many entries can be expensive), upload_to can contain strftime formatting, which will be replaced by the date/time of the upload.

    archivo = models.FileField(upload_to = 'path/%Y/%M/%D/')
    

    You can store the parameter in the instance object:

    def get_file_path(instance, filename):
        ext = filename.split('.')[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        return os.path.join(instance.directory_string_var, filename)
    
    class Archivo(models.Model):
        archivo = models.FileField(upload_to = get_file_path)
        directory_string_var = 'default_directory_string_var'