How to change the file name of an uploaded file in Django?

How are you uploading the file?
I assume with the FileField.

The documentation for FileField.upload_to says that the upload_to field,

may also be a callable, such as a
function, which will be called to
obtain the upload path, including the
filename. This callable must be able
to accept two arguments, and return a
Unix-style path (with forward slashes)
to be passed along to the storage
system. The two arguments that will be
passed are:

instance“: An instance of
the model where the FileField is
defined. More specifically, this is
the particular instance where the
current file is being attached.

filename“:The filename that was
originally given to the file. This may
or may not be taken into account when
determining the final destination
path.

So it looks like you just need to make a function to do your name handling and return the path.

def update_filename(instance, filename):
    path = "upload/path/"
    format = instance.userid + instance.transaction_uuid + instance.file_extension
    return os.path.join(path, format)

Leave a Comment