Renaming files in Django FileField Renaming files in Django FileField django django

Renaming files in Django FileField


I don't think you need to use raw SQL for this. I think you need to rename the file using the os facility, then set the model's FileField name to the new name. Maybe something like:

os.rename(model.direct_file.path, new_path)model.direct_file.name = new_namemodel.save()


The current Django documentation states:

"When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file." See docs for further reading.

Instead of using the Python File object to open the file, you should use FieldFile.open() to open the file, then manipulate the file's path accordingly. Afterward, save the model object, and the changes to the path should persist.


 new_name = 'photos_preview/' + str(uuid.uuid1()) os.rename(photo.image_preview.path, settings.MEDIA_ROOT + new_name) photo.image_preview.name = new_name photo.save()