I know that there is a very similar thread here, but I cannot find the solution to my problem.
I need to rename a file which is save in django models.FileField
I tried this
os.rename(old_path, new_path)
mod.direct_file = File(open(new_path))
mod.save()
And this
mod.direct_file.save(new_path, File(open(old_path)))
os.remove(old_path)
And many other ways, but nothing seemed to help. A new file is created in all ways, however, data in filefield does not change at all.
EDIT: SOLVED
os.rename(old_path, new_path)
cursor = connection.cursor()
cursor.execute("UPDATE mods_mod SET direct_file = %s WHERE id = %s", [new_name, mod.id])
transaction.commit_unless_managed()
You may use the following:
Suppose 'obj' is the django object that you want to rename. Then do this:
obj.file_field_name.name = new_name
obj.save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With