Skip to content

Instantly share code, notes, and snippets.

@sjkingo
Created June 4, 2015 22:56
Show Gist options
  • Save sjkingo/b836272f0757b20f8016 to your computer and use it in GitHub Desktop.
Save sjkingo/b836272f0757b20f8016 to your computer and use it in GitHub Desktop.
Add a product image programatically in Cartridge
filename = 'image.jpg'
source_fp = open(filename, 'rb')
p = Product.objects.get(...)
# Create the ProductImage if it doesn't exist already and assign to Product
images = ProductImage.objects.filter(description=filename)
if len(images) == 0:
the_file = File(source_fp)
the_image = p.images.create(
product=p,
file=the_file,
description=filename)
media_path = the_image.file.path.strip(settings.MEDIA_ROOT)
p.image = media_path
p.save()
# Copy the image over to all the variations
variations = p.variations.all()
for variation in variations:
variation.image = the_image
variation.save()
@sjkingo
Copy link
Author

sjkingo commented Jun 4, 2015

(obviously not a complete example..)

@andrewfam
Copy link

Hey,

Where are you importing the File from?
the_file = File(source_fp)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment