5

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.

2 Answers 2

12

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'
4
  • 1
    thanks man, store the parameter in the instance work for me! :D
    – eos87
    Nov 5, 2010 at 22:51
  • Mind explaining uuid in here? Dec 1, 2018 at 18:25
  • 1
    @RishabhAgrahari You can ignore this - it is a very old answer. The goal here was generating a unique name for every upload - I'm from Brazil where we speak Portuguese and sometimes people upload files with unicode or other characters that may cause problems down the road so I often use a hash or UUID instead of the original name. I probably would use settings.SOMETHING today. Dec 2, 2018 at 0:00
  • This does not seem to work for Django 3.1.7 (way in the future from the original answer)
    – Harlin
    Mar 20, 2021 at 2:11
1

I do it this way:

import uuid
import os

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename_start = filename.replace('.'+ext,'')

    filename = "%s__%s.%s" % (uuid.uuid4(),filename_start, ext)
    return os.path.join('FolderPath', filename)

class Blast_Email(models.Model):
    file    = models.FileField(upload_to=get_file_path,verbose_name=(u'File'))
    ### your other columns

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.