Skip to Content
Menu
This question has been flagged
3 Replies
45299 Views

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

Avatar
Discard
Best Answer

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

Avatar
Discard
Best Answer



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 !

Avatar
Discard
Best Answer
  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.

Avatar
Discard
Related Posts Replies Views Activity
1
Sep 19
10227
0
Mar 15
3332
0
Mar 15
3332
0
Mar 15
3349
1
Dec 22
3316