Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy file from one model to another

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.

like image 219
Andrey Avatar asked Apr 23 '11 14:04

Andrey


2 Answers

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.

like image 139
amjoconn Avatar answered Sep 19 '22 14:09

amjoconn


Although this is late, but I would tackle this problem thus,

class UploadImage(models.Model):     Image = models.ImageField(upload_to="temp/")      # i need to delete the temp uploaded file from the file system when i delete this model           # from the database     def delete(self, using=None):         name = self.Image.name         # i ensure that the database record is deleted first before deleting the uploaded          # file from the filesystem.         super(UploadImage, self).delete(using)         self.Image.storage.delete(name)   class RealImage(models.Model):    Image = models.ImageField(upload_to="real/")   # in my view or where ever I want to do the copying i'll do this import os from django.core.files import File  uploaded_image = UploadImage.objects.get(id=image_id).Image real_image = RealImage() real_image.Image = File(uploaded_image, uploaded_image.name) real_image.save() uploaded_image.close() uploaded_image.delete() 

If I were using a model form to handle the process, i'll just do

# django model forms provides a reference to the associated model via the instance property form.instance.Image = File(uploaded_image, os.path.basename(uploaded_image.path)) form.save() uploaded_image.close() uploaded_image.delete() 

note that I ensure the uploaded_image file is closed because calling real_image.save() will open the file and read its content. That is handled by what ever storage system is used by the ImageField instance

like image 27
Kem Etoh Avatar answered Sep 22 '22 14:09

Kem Etoh