Monday, July 4, 2022

Change user password with function in odoo

In this blog we will explain how to change user password with function in odoo 

Example : 

    We created view with button that call wizard enable user to enter new password and click button to change his password with the new one , so this button must call python function that change his password and this function can be just as bellow 


def change_password(self,user_id,new_password):
        user = self.env['res.users'].search([('id','=',user_id)])
        user.sudo().write({'password':new_password})

Generate access token in odoo

In this blog we will explain how to generate access token in odoo for each user step by step , so 

1- create new class which is inherits res.users class

2- create new char field which will contain the token , and it must be compute field

3- create function to generate the token

as bellow 

from odoo import models, fields, api, _
import hashlib
import hmac
import base64
import string
import math, random
from passlib import pwd, hash


class ResUsers(models.Model):
    _inherit = 'res.users'

    access_token = fields.Char(string="Access Token", readonly=True, compute='generate_access_token')

    def generate_access_token(self):
        for rec in self:
            token = ""

            # first way
            # pre_token = rec.name+rec.login
            # token = hash.pbkdf2_sha512.hash(pre_token)

            # second way
            hash_object = hashlib.sha256(rec.password.encode())
            token = hash_object.hexdigest()

            rec.sudo().write({'access_token': token})


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')

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