Monday, July 4, 2022

Create url for image in odoo


Let us say we are building an APIs for our odoo system and we have to build api to return the product data and we must return the product image as url so we can create function that generate this url as bellow

 

First :

 
@http.route(['/web/product_image',
        '/web/product_image/<int:rec_id>',
        '/web/product_image/<int:rec_id>/<string:field>',
        '/web/product_image/<int:rec_id>/<string:field>/<string:model>/'], type='http', auth="public")
    def content_image_partner(self, rec_id, field='image_128', model='product.template', **kwargs):
        return self._content_image(id=rec_id, model='product.template', field=field,
            placeholder='user_placeholder.jpg') 

 

 Second :

def _content_image(self, xmlid=None, model='ir.attachment', id=None, field='datas',
                       filename_field='name', unique=None, filename=None, mimetype=None,
                       download=None, width=0, height=0, crop=False, quality=0, access_token=None,
                       placeholder=None, **kwargs):
        status, headers, image_base64 = request.env['ir.http'].binary_content(
            xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename,
            filename_field=filename_field, download=download, mimetype=mimetype,
            default_mimetype='image/png', access_token=access_token)

        return Binary._content_image_get_response(
            status, headers, image_base64, model=model, id=id, field=field, download=download,
            width=width, height=height, crop=crop, quality=quality,
            placeholder=placeholder)

 

Third : 

def generate_product_image_url(self,product_id):
        img_url = ''
        # or we can set default image for each product as
        # img_url = 'http://'+request.httprequest.__dict__['environ']['HTTP_HOST']+'/module_name/static/src/img/default.png'
        request.env.cr.execute(
            "SELECT id FROM ir_attachment WHERE res_model='product.template' and res_id=%s",[product_id]
        )
        if request.env.cr.fetchone():
            img_url_pre = 'http://'+request.httprequest.__dict__['environ']['HTTP_HOST']+'/web/product_image/%s/image_1920/product.template' % product_id,
            img_url = img_url_pre[0]
                
        return img_url

No comments:

Post a Comment

Odoo Invoice Qr code issues

There are two main issues must of us facing with the QR code in Odoo invoice & these issues are 1/ QR code displayed as broken image w...