How to Change the File Name of an Uploaded File in Django

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)

Change filename before save file in Django

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'

Django File Upload and Rename

You just need to change your content_file_name function. The function below will create paths like so: uploads/42_100.c, where 42 is the user's id, and 100 is the question's id.

import os
def content_file_name(instance, filename):
ext = filename.split('.')[-1]
filename = "%s_%s.%s" % (instance.user.id, instance.questid.id, ext)
return os.path.join('uploads', filename)

Django/Python: How to change filename when saving file using models.FileField?

Could you perhaps call save() on the form with commit=False, set the name on the Document file, and then save the Document? For example:

def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
document = form.save(commit=False)
document.name = 'some_new_name'
document.save()
return redirect('model_form_upload')
else:
form = DocumentForm()
return render(request, 'model_form_upload.html', {'form': form})

Django How to rename file upload by can change path?

If you take a look at the django docs you will see that the the upload_to attribute is a callable.

Specifically note how user_directory_path is called: models.FileField(upload_to=user_directory_path). There are no arguments and no method call ().

def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)

Your function will need to be something like, so it returns a callable (please note I havent tested this):

def path_and_rename(path):
def path_and_rename_func(instance, filename):
upload_to = path
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(upload_to, filename)
return path_and_rename_func


image=models.ImageField(upload_to=path_and_rename("path_image1"))

Django / Python : Change uploaded filename before saving file

You need to define upload_to function.

Django ImageField change file name on upload

You can pass a function into upload_to field:

def f(instance, filename):
ext = filename.split('.')[-1]
if instance.pk:
return '{}.{}'.format(instance.pk, ext)
else:
pass
# do something if pk is not there yet

My suggestions would be to return a random filename instead of {pk}.{ext}. As a bonus, it will be more secure.

What happens is that Django will call this function to determine where the file should be uploaded to. That means that your function is responsible for returning the whole path of the file including the filename. Below is modified function where you can specify where to upload to and how to use it:

import os
from uuid import uuid4

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

FileField(upload_to=path_and_rename('upload/here/'), ...)


Related Topics



Leave a reply



Submit