diff --git a/product_import/models/product_url.py b/product_import/models/product_url.py index 9e4f3f5e8..6d0fcf755 100644 --- a/product_import/models/product_url.py +++ b/product_import/models/product_url.py @@ -21,32 +21,73 @@ ############################################################################# import requests import base64 -from odoo import models, fields, api +from odoo import models, fields, api, _ +from odoo.exceptions import UserError class ProductImage(models.Model): _inherit = 'product.template' image_url = fields.Char(string='Image URL') + image_added = fields.Binary("Image (1920x1920)", + compute='_compute_image_added', store=True) - @api.onchange('image_url') - def _onchange_image_url(self): - """ function to load image from URL """ + @api.depends('image_url') + def _compute_image_added(self): + """ Function to load an image from URL or local file path """ image = False if self.image_url: - image = base64.b64encode(requests.get(self.image_url).content) - self.image_1920 = image + if self.image_url.startswith(('http://', 'https://')): + # Load image from URL + try: + image = base64.b64encode( + requests.get(self.image_url).content) + except Exception as e: + # Handle URL loading errors + raise UserError(_(f"Error loading image from URL: {str(e)}")) + else: + # Load image from local file path + try: + with open(self.image_url, 'rb') as image_file: + image = base64.b64encode(image_file.read()) + except Exception as e: + # Handle local file loading errors + raise UserError( + _(f"Error loading image from local path: {str(e)}")) + image_added = image + if image_added: + self.image_1920 = image_added class ProductVariantImage(models.Model): _inherit = 'product.product' image_url = fields.Char(string='Image URL') + image_added = fields.Binary("Image (1920x1920)", + compute='_compute_image_added', store=True) - @api.onchange('image_url') - def _onchange_image_url(self): - """ function to load image from URL in product variant""" + @api.depends('image_url') + def _compute_image_added(self): + """ Function to load an image from URL or local file path """ image = False if self.image_url: - image = base64.b64encode(requests.get(self.image_url).content) - self.image_1920 = image \ No newline at end of file + if self.image_url.startswith(('http://', 'https://')): + # Load image from URL + try: + image = base64.b64encode( + requests.get(self.image_url).content) + except Exception as e: + # Handle URL loading errors + raise UserError(_(f"Error loading image from URL: {str(e)}")) + else: + # Load image from local file path + try: + with open(self.image_url, 'rb') as image_file: + image = base64.b64encode(image_file.read()) + except Exception as e: + # Handle local file loading errors + raise UserError( + _(f"Error loading image from local path: {str(e)}")) + image_added = image + if image_added: + self.image_1920 = image_added