django - How to copy the actual image file from one model to another?

988 views
Skip to first unread message

Aamu Padi

unread,
Nov 8, 2013, 12:02:25 PM11/8/13
to django...@googlegroups.com
I want to copy images from one model to another within the project. Suppose these are my models:

    class BackgroundImage(models.Model):
        user = models.ForeignKey(User)
        image = models.ImageField(upload_to=get_upload_file_name)
        caption = models.CharField(max_length=200)
        pub_date = models.DateTimeField(default=datetime.now)


    class ProfilePicture(models.Model):
        user = models.ForeignKey(User)
        image = models.ImageField(upload_to=get_upload_file_name)
        caption = models.CharField(max_length=200)
        pub_date = models.DateTimeField(default=datetime.now)

        @classmethod
            def create_from_bg(cls, bg_img):
                img = cls(user=bg_img.user, image=bg_img.image, caption=bg_img.caption+'_copy', pub_date=bg_img.pub_date)
                img.save()
                return img

For now, I can do these:

To get the user
    >>>m = User.objects.get(username='m')
   
To get the user's profile picture set
    >>>m_pro_set = m.profilepicture_set.all()
    >>>m_pro_set
    [<ProfilePicture: pro_mik>]


Get an image object from Background image of the user
    >>>m_back_1 = m.backgroundimage_set.get(id=2)
    >>>m_back_1
    <BackgroundImage: bg_mik>


And then:
    >>>profile_pic = ProfilePicture.create_from_bg(m_back_1)

Now when I check it, it does create a new instance.
    >>>m_pro_set
    [<ProfilePicture: pro_mik>,<ProfilePicture: bg_mik>]



But, if I check on the path, and even on the media folder, its the same image and not an actual copy of the image file in the folder or disk.

    >>>profile_pic.image
    <ImageFileField: uploaded_files/1389904144_ken.jpg>
    >>>m_back_1.image
    <ImageFileField: uploaded_files/1389904144_ken.jpg>


What it does is, when I save a new instance of the image, it creates a new instance of that same image, and not creates a new file in the disk, i.e. there's no actual copying of the file in the directory.
How do I go about to actually copy the original image `file` within the models? Any help will be much appreciated! Thank you.
Reply all
Reply to author
Forward
0 new messages