Monday, July 4, 2022

Create url for pdf file in odoo

 

In this blog we will explain how to create url for pdf file in odoo


for an example : we want to generate url for the pdf invoice , so we can create function that takes the invoice id and return the url for the pdf invoice as bellow 

 

from odoo import api , fields, models,SUPERUSER_ID,_

    def generate_pdf_invoice_url(self , invoice_id):

        # pdf = request.env.ref('module_name.report_action_id').with_user(SUPERUSER_ID)._render_qweb_pdf([invoice_id.id])
        pdf = request.env.ref('account.account_invoices').with_user(SUPERUSER_ID)._render_qweb_pdf([invoice_id.id])

        pdf_invoice = request.env['ir.attachment'].sudo().create({
            'name': invoice_id.name,
            'type': 'binary',
            'datas': base64.b64encode(pdf[0]),
            'store_fname': invoice_id.name,
            'res_model': 'account.payment',
            'res_id': invoice_id.id,
            'mimetype': 'application/x-pdf'
        })
        pdf_file_url + 'http://'+request.httprequest.__dict__['environ']['HTTP_HOST']+'/web/content/%s' % (pdf_invoice.id)
        
        return pdf_file_url
           

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

Load image from binary file in odoo

 


In this blog we will give an example how to load image from binary file in odoo using http controller function

    so let us say that we made an integration with external api to get new customer data with is include image_file and we want to save this image into odoo database , so first we must create function that takes the image_file as an input and return the image as data (read the binary file), second we can pass the image data to image field in res.partner object in odoo to create new customer with image , and the function can be just as bellow 

 

def load_image_from_binary_file(self, file):
        return base64.b64encode(file.read())

Load image from url in odoo


In this blog we will give an example how to load image from url in odoo using http controller function

    so let us say that we made an integration with external api to get new customer data with is include image_url field and we want to save this image into odoo database , so first we must create function that takes the image_url as an input and return the image as data , second we can pass the image data to image field in res.partner object in odoo to create new customer with image , and the function can be just as bellow 

 

def load_image_from_url(self, url):
        data = base64.b64encode(requests.get(url.strip()).content).replace(b'\n', b'')
        return data

current url in odoo


 

if we want to get the server URL for the current odoo module we can get it as below
 

#for python model 

server_url = self.env['ir.config_parameter'].get_param('web.base.url')

 

#for http.controller

1/ from odoo.http import request

2/ server_url = request.env['ir.config_parameter'].get_param('web.base.url')

Saturday, April 16, 2022

TypeError: Object of type datetime is not JSON serializable

 

This error "TypeError: Object of type datetime is not JSON serializable" happens when we try to convert data with date time into json dictionary , so to fix this error we have to convert the data to string first then put it in the dictionary and then we can convert the dictionary to json format
...
for example if we want to create api with odoo to return the data for sale order , so we can put the sale order data as bellow 

order_data = {
            'id':order_id.id,
            'name':order_id.name,
            'customer':{'id':order_id.partner_id.id,'name':order_id.partner_id.name},
            'salesperson':{'id':order_id.user_id.id,'name':order_id.user_id.name},
            'date_order':str(order_id.date_order),
            'state':order_id.state,
            'products':order_products,
            'untaxed_amount':order_id.amount_untaxed,
            'total_tax': order_id.amount_tax,
            'total_amount':order_id.amount_total,
     }

return Response(json.dumps(order_data),headers=headers)

ssh

In this blog we will explain some commands to deal with remote server from ubuntu terminal using SSH

1: Connect to remote server using ssh by the command bellow 

     sudo ssh remote_user_name@remote_ip

 

2: Connect to remote server with key.pem using ssh by the command bellow

    sudo ssh remote_user_name@remote_ip -i /path/key.pem

 

3/ copy folder with it's content from the remote server to local device

    sudo scp -r remote_user@remote_server_ip:/opt/example /home/local_folder

    sudo scp -i /path/key.pem -r remote_user@remote_server_ip:/opt/example /home/local_folder

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...