Amandasaurus
Amandasaurus

Reputation: 60699

Copy the contents of an ImageField to a new file path in Django

I have a Django model object that has a few normal attributes, and it has a ImageField for the logo. I want to write a method that'll copy this object to a new object. It's easy enough to instanciate the new object, then loop over all the attributes and copy from the old to new (e.g. new_object.name = old_object.name). However if I do that with the logo field (i.e. new_object.logo = old_object.logo), both new_object and old_object point to the same file on the harddisk. If you edit the old file, the logo for the new object will change.

What's the best way to have a full/deep copy of the ImageField? I want it to have a different file name and to point to a different file on the disk, but it should have exactly the same content.

Upvotes: 4

Views: 4116

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

Why not create a function that is fun on the save signal which copies the image file to whereever you want, then creates a new object with a new image field?

models.py

class ObjectOne(models.Model):
    logo = models.ImageField(...)

class ObjectTwo(models.Model):
    logo = models.ImageField(...)

from django.db.models.signals import post_save
from signals import my_signal
post_save.connect(my_signal, dispatch_uid="001")

signals.py

from models. import ObjectOne, ObjectTwo
def my_signal(sender, instance, *args, **kwargs):
    if sender is ObjectOne:
        new_obj = ObjectTwo()
        new_obj.logo.save("custom/path/new_filename.jpg",File(open(instance.image.url,"w"))
        new_obj.save()

I haven't tested the image copying code but this is the general idea. There is more here:

Programmatically saving image to Django ImageField

Django: add image in an ImageField from image url

how to manually assign imagefield in Django

Upvotes: 3

Related Questions