amannn
amannn

Reputation: 45

python, django: copy image

I created this function, to copy an image from a django-model to another django-model. The image has to be saved redundantly:

def __copy_file__(from_object,to_object,field):
    attr = field.attname
    try:
        newpath = getattr(from_object,attr).path
        dot_at = newpath.rfind(".")
        while os.path.exists(newpath):
            newpath = newpath[:dot_at] + "_" + newpath[dot_at:]
        shutil.copyfile(getattr(from_object,attr).path, newpath)
        getattr(to_object,attr).save(newpath, File(open(getattr(from_object,attr).path)))
        return True
    except ValueError:
        return False

But this function creates somehow invalid files.. I can remember it worked one day, but i tested it today and it isn't working anymore..

Edit: Now i know that the function produces two images. One that works and one that doesn't. The line shutil.copyfile (etc) produces the working one and in the assignment getattr(to_object,attr).save (etc) the image gets saved again. So this is the problem. It should just be assigned, not copied again..

Can anybody help me? :)

Upvotes: 2

Views: 1372

Answers (1)

Julian
Julian

Reputation: 702

the way I do it, assuming from_model and to_model are to models instances with an image ImageField:

def copy_image(from_model, to_model):
    to_model.image.save(from_model.image.url.split('/')[-1],from_model.image.file,save=True)

Upvotes: 3

Related Questions