Renaming Files in Django FileField

I know that there is a very similar thread here, but I can not find a solution to my problem.

I need to rename a file that is saved in django models. Filefield

I tried this

os.rename(old_path, new_path)
mod.direct_file = File(open(new_path))
mod.save()

And this one

mod.direct_file.save(new_path, File(open(old_path)))
os.remove(old_path)

And many other ways, but nothing helped. A new file is created in every way, but the data in the file field 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()
+5
source share
4 answers

I do not think you need to use raw SQL for this. I think you need to rename the file using the tool os, and then set the model name FileFieldfor the new name. Maybe something like:

os.rename(model.direct_file.path, new_path)
model.direct_file.name = new_name
model.save()
+6
source

The current Django documentation states:

" , FieldFile ". docs.

, Python File , FieldFile.open(), , . , .

+3
 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()
+1

, blobs, django , . .

.picture.path .picture.file. * , . instance.picture.name - .picture.file. *, .

ImageField , :

( django 1.10)

import imghdr
import os

from django.db import models

class MyModel(models.Model):
    picture = models.ImageField()

instance = MyModel.objects.first()
if os.path.exists(instance.picture.path):
    extension = imghdr.what(instance.picture.path)
    os.rename(instance.picture.path, instance.picture.path + '.' + extension)
    instance.picture = instance.picture.name + '.' + extension
    instance.save()
+1

All Articles