diff --git a/addons/website_sale/models/product_image.py b/addons/website_sale/models/product_image.py index 562ebe79854..5fe484a6a5c 100644 --- a/addons/website_sale/models/product_image.py +++ b/addons/website_sale/models/product_image.py @@ -41,3 +41,23 @@ class ProductImage(models.Model): for image in self: if image.video_url and not image.embed_code: raise ValidationError(_("Provided video URL for '%s' is not valid. Please enter a valid video URL.") % image.name) + + @api.model_create_multi + def create(self, vals_list): + """ + We don't want the default_product_tmpl_id from the context + to be applied if we have a product_variant_id set to avoid + having the variant images to show also as template images. + But we want it if we don't have a product_variant_id set. + """ + context_without_template = self.with_context({k: v for k, v in self.env.context.items() if k != 'default_product_tmpl_id'}) + normal_vals = [] + variant_vals_list = [] + + for vals in vals_list: + if vals.get('product_variant_id') and 'default_product_tmpl_id' in self.env.context: + variant_vals_list.append(vals) + else: + normal_vals.append(vals) + + return super().create(normal_vals) + super(ProductImage, context_without_template).create(variant_vals_list) diff --git a/addons/website_sale/tests/test_website_sale_image.py b/addons/website_sale/tests/test_website_sale_image.py index fd16de4c76f..5a1d56f6f37 100644 --- a/addons/website_sale/tests/test_website_sale_image.py +++ b/addons/website_sale/tests/test_website_sale_image.py @@ -229,3 +229,30 @@ class TestWebsiteSaleImage(odoo.tests.HttpCase): self.assertEqual(images[1].image_1920, red_image) self.assertEqual(images[2].image_1920, image_gif) self.assertEqual(images[3].image_1920, image_svg) + + # CASE: When uploading a product variant image + # we don't want the default_product_tmpl_id from the context to be applied if we have a product_variant_id set + # we want the default_product_tmpl_id from the context to be applied if we don't have a product_variant_id set + + additionnal_context = {'default_product_tmpl_id': template.id} + + product = self.env['product.product'].create({ + 'product_tmpl_id': template.id, + }) + + product_image = self.env['product.image'].with_context(**additionnal_context).create([{ + 'name': 'Template image', + 'image_1920': red_image, + }, { + 'name': 'Variant image', + 'image_1920': blue_image, + 'product_variant_id': product.id, + }]) + + template_image = product_image.filtered(lambda i: i.name == 'Template image') + variant_image = product_image.filtered(lambda i: i.name == 'Variant image') + + self.assertEqual(template_image.product_tmpl_id.id, template.id) + self.assertFalse(template_image.product_variant_id.id) + self.assertFalse(variant_image.product_tmpl_id.id) + self.assertEqual(variant_image.product_variant_id.id, product.id)