controllerodooodoo-16

Odoo : Get current model informations in the controller


I'm building a custom addon for Odoo which add a page on res.partner.form to display data from an external API.

Here is my code

views/my_view.xml

<data>
    <record id = "onglet_factu" model = "ir.ui.view">
        <field name = "name">La Factu</field>
        <field name = "model">res.partner</field>
        <field name = "inherit_id" ref = "base.view_partner_form"/>
        <field name = "arch" type = "xml">
            <xpath expr="//page[@name='internal_notes']" position='after'>
                <page string='Onglet API'>
                    <h2>Fake API</h2>
                    <field name="data" widget="my_widget"/>
                </page>
            </xpath>
        </field>
    </record>

then I add the new field in my model

from odoo import models, fields

models/api.py

class Api(models.Model):
    _inherit = 'res.partner'
    data = fields.Char()

I use a javascript class to make the API call via a controller and display in a Qweb template

static/src/js/api_component.js

export class MyApiField extends Component {
    setup() {
        super.setup();
        onWillStart(async () => {
            var id = this.env.model.root.data.id
            fetch('/napsis_factu/test?id='+id)
                .then(response => response.json())
                .then((data) => {
                    console.log(data);
                    this.state.data  = {
                        data1 : data['data1'],
                        data2: data['data2']
                    }
                })
                .catch((err) => {
                    console.log(err.message);
                });
        })

    }

}

MyApiField.template = "addon.template";
MyApiField.props = {
    ...standardFieldProps,
};
MyApiField.supportedTypes = ["char"];

export const apiField = { component: MyApiField };
registry.category("fields").add("my_text_field", apiField);

And here is the controller call in the javascript class :

controllers/api_call.py

@http.route('/myaddon/api-call', auth='user', csrf=False )
  def calling(self, **kwargs):
    theId = # How to get the ID of the res partner object I'm on ??
    payload = {   "Ctxt": "xxxxxxxxxxxxx",
                    "ID": theId,
                    }
    req = urllib.request.Request(url='https://myapi', headers={
        "Content-Type":"application/json"}, data = json.dumps(payload).encode())
    reply = json.loads(urllib.request.urlopen(req).read().decode('UTF-8'))
    if reply.get("error"):
     print('Alert!!')
     raise Exception(reply["error"])
    return json.dumps(reply) 

I'm wondering if it would be possible to get, within the controller, the informations of the current model. Now I pass this via my javascript call but would it be possible to get the ID of the res.parner.form.view I'm on ? Do you know how to do it ?

Thanks !


Solution

  • You can use odoo.http.request and the partner id passed throw the kwargs parameter to get the partner record

    Example:

    partner_id = int(kwargs.get('id', 0))
    partner = request.env['res.partner'].browse(partner_id)
    

    You can find an example in website_profile module