copy file from one model to another

Andrey picture Andrey · Apr 23, 2011 · Viewed 14.1k times · Source

I have 2 simple models:

class UploadImage(models.Model):
   Image = models.ImageField(upload_to="temp/")

class RealImage(models.Model):
   Image = models.ImageField(upload_to="real/")

And one form

class RealImageForm(ModelForm):
    class Meta:
        model = RealImage 

I need to save file from UploadImage into RealImage. How could i do this. Below code doesn't work

realform.Image=UploadImage.objects.get(id=image_id).Image 
realform.save()

Tnx for help.

Answer

amjoconn picture amjoconn · Jun 4, 2012

Inspired by Gerard's solution I came up with the following code:

from django.core.files.base import ContentFile

#...

class Example(models.Model):
    file = models.FileField()

    def duplicate(self):
        """
        Duplicating this object including copying the file
        """
        new_example = Example()
        new_file = ContentFile(self.file.read())
        new_file.name = self.file.name
        new_example.file = new_file
        new_example.save()

This will actually go as far as renaming the file by adding a "_1" to the filename so that both the original file and this new copy of the file can exist on disk at the same time.