def create_image(instance, filename): image_class = BaseImage.find_subclass(parent_model=instance) image_field = image_class._meta.get_field("image") image_path = image_field.generate_filename(instance, filename) # Copy the image into the storage if it isn't there: if not image_field.storage.exists(image_path): # pragma: no cover with open(os.path.join(IMAGE_SOURCE_PATH, filename), "rb") as infp: image_field.storage.save(image_path, infp) image = image_class(title=filename, **{image_class.parent_field: instance}) image.image.name = image_path image.save() assert image.image.name == image_path return image
def import_image(target, datum, position): ImageModel = BaseImage.find_subclass(target) image_path = datum.pop("filename") updated_at = datum.pop("updated_at", None) created_at = datum.pop("created_at", None) i_args = { ImageModel.parent_field: target, "created_at": parse_aware_datetime(created_at), "modified_at": parse_aware_datetime(updated_at or created_at), "caption": datum.pop("caption"), "ordering": position } image = ImageModel(**i_args) image.image.name = image_path if not image.image.storage.exists(image.image): # pragma: no cover log.warn("Image %s (for %r) not in storage -- continuing anyway", image_path, target) image.save() return image