Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming files in Django FileField

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()
like image 560
aemdy Avatar asked Sep 10 '12 20:09

aemdy


1 Answers

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()

like image 145
user8446586 Avatar answered Oct 18 '22 18:10

user8446586