콘텐츠로 건너뛰기
메뉴
커뮤니티에 참여하려면 회원 가입을 하시기 바랍니다.
신고된 질문입니다
3 답글
45476 화면

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

아바타
취소
베스트 답변

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

아바타
취소
베스트 답변



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 !

아바타
취소
베스트 답변
  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.

아바타
취소
관련 게시물 답글 화면 활동
1
9월 19
10418
0
3월 15
3590
0
3월 15
3445
0
3월 15
3462
1
12월 22
3416