Passa al contenuto
Odoo Menu
  • Accedi
  • Provalo gratis
  • App
    Finanze
    • Contabilità
    • Fatturazione
    • Note spese
    • Fogli di calcolo (BI)
    • Documenti
    • Firma
    Vendite
    • CRM
    • Vendite
    • Punto vendita Negozio
    • Punto vendita Ristorante
    • Abbonamenti
    • Noleggi
    Siti web
    • Configuratore sito web
    • E-commerce
    • Blog
    • Forum
    • Live chat
    • E-learning
    Supply chain
    • Magazzino
    • Produzione
    • PLM
    • Acquisti
    • Manutenzione
    • Qualità
    Risorse umane
    • Dipendenti
    • Assunzioni
    • Ferie
    • Valutazioni
    • Referral dipendenti
    • Parco veicoli
    Marketing
    • Social marketing
    • E-mail marketing
    • SMS marketing
    • Eventi
    • Marketing automation
    • Sondaggi
    Servizi
    • Progetti
    • Fogli ore
    • Assistenza sul campo
    • Helpdesk
    • Pianificazione
    • Appuntamenti
    Produttività
    • Comunicazioni
    • Approvazioni
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    App di terze parti Odoo Studio Piattaforma cloud Odoo
  • Settori
    Retail
    • Libreria
    • Negozio di abbigliamento
    • Negozio di arredamento
    • Alimentari
    • Ferramenta
    • Negozio di giocattoli
    Cibo e ospitalità
    • Bar e pub
    • Ristorante
    • Fast food
    • Pensione
    • Grossista di bevande
    • Hotel
    Agenzia immobiliare
    • Agenzia immobiliare
    • Studio di architettura
    • Edilizia
    • Gestione immobiliare
    • Impresa di giardinaggio
    • Associazione di proprietari immobiliari
    Consulenza
    • Società di contabilità
    • Partner Odoo
    • Agenzia di marketing
    • Studio legale
    • Selezione del personale
    • Audit e certificazione
    Produzione
    • Tessile
    • Metallo
    • Arredamenti
    • Alimentare
    • Birrificio
    • Ditta di regalistica aziendale
    Benessere e sport
    • Club sportivo
    • Negozio di ottica
    • Centro fitness
    • Centro benessere
    • Farmacia
    • Parrucchiere
    Commercio
    • Tuttofare
    • Hardware e assistenza IT
    • Ditta di installazione di pannelli solari
    • Calzolaio
    • Servizi di pulizia
    • Servizi di climatizzazione
    Altro
    • Organizzazione non profit
    • Ente per la tutela ambientale
    • Agenzia di cartellonistica pubblicitaria
    • Studio fotografico
    • Punto noleggio di biciclette
    • Rivenditore di software
    Carica tutti i settori
  • Community
    Apprendimento
    • Tutorial
    • Documentazione
    • Certificazioni 
    • Formazione
    • Blog
    • Podcast
    Potenzia la tua formazione
    • Programma educativo
    • Scale Up! Business Game
    • Visita Odoo
    Ottieni il software
    • Scarica
    • Versioni a confronto
    • Note di versione
    Collabora
    • Github
    • Forum
    • Eventi
    • Traduzioni
    • Diventa nostro partner
    • Servizi per partner
    • Registra la tua società di contabilità
    Ottieni servizi
    • Trova un partner
    • Trova un contabile
    • Incontra un esperto
    • Servizi di implementazione
    • Testimonianze dei clienti
    • Supporto
    • Aggiornamenti
    GitHub Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Richiedi una demo
  • Prezzi
  • Aiuto

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilità
  • Magazzino
  • PoS
  • Progetti
  • MRP
All apps
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
Assistenza

How to call a python function from JavaScript?

Iscriviti

Ricevi una notifica quando c'è un'attività per questo post

La domanda è stata contrassegnata
javascriptpython
3 Risposte
47160 Visualizzazioni
Avatar
Sreedath Namangalam

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

3
Avatar
Abbandona
Avatar
Omal Bastin
Risposta migliore

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

2
Avatar
Abbandona
Avatar
Shameem Babu
Risposta migliore



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
Avatar
Abbandona
Avatar
mike
Risposta migliore
  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.

0
Avatar
Abbandona
Ti stai godendo la conversazione? Non leggere soltanto, partecipa anche tu!

Crea un account oggi per scoprire funzionalità esclusive ed entrare a far parte della nostra fantastica community!

Registrati
Post correlati Risposte Visualizzazioni Attività
No handler found error on email validation?
javascript python
Avatar
Avatar
1
giu 25
4917
How to call a java script function from python ?
javascript python
Avatar
Avatar
1
set 19
11734
Invoking javascript methods from python
javascript python
Avatar
0
mar 15
4855
No handler found error on email field validation ?
javascript python
Avatar
0
mar 15
4660
Call wizard view in js function
javascript python odoo
Avatar
Avatar
1
dic 22
4336
Community
  • Tutorial
  • Documentazione
  • Forum
Open source
  • Scarica
  • Github
  • Runbot
  • Traduzioni
Servizi
  • Hosting Odoo.sh
  • Supporto
  • Aggiornamenti
  • Sviluppi personalizzati
  • Formazione
  • Trova un contabile
  • Trova un partner
  • Diventa nostro partner
Chi siamo
  • La nostra azienda
  • Branding
  • Contattaci
  • Lavora con noi
  • Eventi
  • Podcast
  • Blog
  • Clienti
  • Note legali • Privacy
  • Sicurezza
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo è un gestionale di applicazioni aziendali open source pensato per coprire tutte le esigenze della tua azienda: CRM, Vendite, E-commerce, Magazzino, Produzione, Fatturazione elettronica, Project Management e molto altro.

Il punto di forza di Odoo è quello di offrire un ecosistema unico di app facili da usare, intuitive e completamente integrate tra loro.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now