Odoo Help

3

How to call a python function from JavaScript?

By
Sreedath Namangalam
on 7/8/13, 7:13 AM 12,379 views

I want to call a python function from JavaScript for writing some values to the DB. How can I do that?

1

Omal Bastin

--Omal Bastin--
1186
| 6 6 8
Kochi, Kerala, India
--Omal Bastin--

Swiming deep into openERP/ODOO

Omal Bastin
On 9/30/13, 11:20 AM

you can use call function or get_func in javascript to call a python function. for example in javascript new instance.web.Model(<model.name.in.quotes>).get_func(<yourfunction_name>)(<arguments>)

0

Shameem iWesabe

--Shameem iWesabe--
890
| 5 3 5
الخبر, Saudi Arabia
--Shameem iWesabe--

Activities     :    Youtube

                           Stackoverflow 

Experience

           iWesabe                                  ◉

           Axon Communications        ❍

           Cybrosys Technologies        ❍


Shameem iWesabe
On 3/14/17, 7:28 AM



In Javascript

odoo.define('custom_module.my_javascript', function (require) {"use strict";
     var Model = require('web.Model')
     
var custom_model = new Model('custom.model') custom_model.call('my_function')
 
});

In Python

from odoo import models, fields, api 

class CustomModel(models.Model):
_name = 'custom.model'
     
     # .............

@api.model
     def my_function(self):
print 'fooooooooooooooo'
You can watch this on YouTube

Thanks !

0
mike
On 7/8/13, 10:37 AM
  1. Add jQuery
  2. Find an existing python method you want to call or write one yourself.
  3. Modify and use js method below.

    function setMessageRead(messageId){ $.ajax({ type: "POST", url: "/web/dataset/call_kw", // URL of OpenERP Handler contentType: "application/json; charset=utf-8", dataType: "json", data: '{"jsonrpc":"2.0","method":"call","params":{"model":"mail.message","method":"set_message_read","args":[[' + messageId + '],true,true,{"default_model":false,"default_res_id":0,"default_parent_id":' + messageId + '}],"kwargs":{},"session_id":"' + sessionid + '","context":{"lang":"en_US","tz":"EST","uid":' + responseData['uid'] + '}},"id":""}', // script call was not successful error: function(XMLHttpRequest, textStatus, errorThrown) { }, // error // script call was successful // data contains the JSON values returned by OpenERP success: function(data){ if (data.result && data.result.error) { // script returned error $('div#loginResult').text("Warning: " + data.result.error); $('div#loginResult').addClass("notice"); } else if (data.error) { // OpenERP error $('div#loginResult').text("Error-Message: " + data.error.message + " | Error-Code: " + data.error.code + " | Error-Type: " + data.error.data.type); $('div#loginResult').addClass("error"); } // if else { // successful transaction // do something successful! } //else } // success }); // ajax };

NOTE: This WYSIWYG widget does not do preformatted on javascript for some reason....

This method can be made more reusable by passing the JSON and URL in as parameters. The DIV loginResult is not necessary. It is just to display errors so you can remove it and send those errors to log or a dialog box. The real trick here is in the JSON -

{"jsonrpc":"2.0",
 "method":"call",
 "params":{"model":"mail.message",
           "method":"set_message_read",
           "args":[[193],
                   true,
                   true,
                   {"default_model":false,
                    "default_res_id":0,
                    "default_parent_id":193}
                  ],
           "kwargs":{},
           "session_id":"303ae4c1bd9d49079c4efc9e06e0184f",
           "context":{"lang":"en_US","tz":"EST","uid":12}},
 "id":"r22"}

The params object set the Python model and method to call and supply required args. It is easy to use Firebug to inspect OpenERP transactions to see which args are required and what values are expected. In this example I am setting the read flag on messages within OpenERP. Create and Update methods will mostly use the web/dataset/call_kw endpoint. Reading data is best using /web/dataset/search_read where you can set the domain and have control over sort, limit, offset and fields. You can find more about this in addons/web/controllers/main.py.

function setMessageRead(messageId){
  $.ajax({
    type: "POST",
    url: "/web/dataset/call_kw", // URL of OpenERP Handler
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: '{"jsonrpc":"2.0","method":"call","params":{"model":"mail.message","method":"set_message_read","args":[[' + messageId + '],true,true,{"default_model":false,"default_res_id":0,"default_parent_id":' + messageId + '}],"kwargs":{},"session_id":"' + sessionid + '","context":{"lang":"en_US","tz":"EST","uid":' + responseData['uid'] + '}},"id":"DBE"}',
    // script call was *not* successful
    error: function(XMLHttpRequest, textStatus, errorThrown) { 

    }, // error 
    // script call was successful 
    // data contains the JSON values returned by OpenERP 
    success: function(data){
      if (data.result && data.result.error) { // script returned error
            $('div#loginResult').text("Warning: " + data.result.error);
            $('div#loginResult').addClass("notice");
        }
        else if (data.error) { // OpenERP error
            $('div#loginResult').text("Error-Message: " + data.error.message + " | Error-Code: " + data.error.code + " | Error-Type: " + data.error.data.type);
            $('div#loginResult').addClass("error");
      } // if
      else { // successful transaction
            // do something successful!
      } //else
    } // success
  }); // ajax
};

NOTE: The WYSIWYG widget for posting prefers Windows style EOL for preformatted style.

About This Community

This platform is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

Register

Odoo Training Center

Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.

Test it now

Question tools

0 follower(s)

Stats

Asked: 7/8/13, 7:13 AM
Seen: 12379 times
Last updated: 3/14/17, 7:28 AM