Search code examples
pythonxmlodooodoo-10

How bind Python class with record's form on Odoo?


I'm creating a new view to user create a record of a object inside a module, so I've created the <record> on .xml and a class python on .py file to bind the fields' <record> with python variables. Problem is that when I run the erros occurs:

Model not found: new.activity.type

Error context:
View `New Activity Type`
[view_id: 771, xml_id: vz_custom_activities.custom_activities_new_activity_type, model: new.activity.type, parent_id: n/a]
None" while parsing /Users/augustosansoncadini/odoo_dev/git/addons/vz_custom_activities/views/views.xml:35, near
<record id="custom_activities_new_activity_type" model="ir.ui.view">
      <field name="name">New Activity Type</field>
      <field name="model">new.activity.type</field>
      <field name="arch" type="xml">
        <form>
          <group>
            <field name="name"/>
          </group>
        </form>
      </field>
    </record>

views.xml

<record id="custom_activities_new_activity_type" model="ir.ui.view">
  <field name="name">New Activity Type</field>
  <field name="model">new.activity.type</field>
  <field name="arch" type="xml">
    <form>
      <group>
        <field name="name"/>
      </group>
    </form>
  </field>
</record>

new_activity_type.py

from odoo import models, fields, api

class new_activity_type(models.Model):
    _name = 'new.activity.type'

    name = fields.Text('Name')

__init__.py

# -*- coding: utf-8 -*-

from . import controllers
from . import models

Solution

  • You have imported your models directory with relative path, which is okay, but you also need to remember python modules (.py files) inside your models have to be imported in the models directory __init__.py file using relative path. That way, whenever your module is installed in odoo, odoo will import the modules root directory __init__.py, all of the models definition in the .py files will get imported.

    This is not just for models directory but any other directories also, you have to import .py to get those python codes working. For example, controllers, wizards, reports directory .py files also, if there are any. This works in following way: whenever a package in Python gets imported, __init.py__ files get executed automatically, so the execution goes like following:

    addons root dir __init__.py >> models dir __init__.py >> all .py files that are imported in that file.

    In your models directory, create __init__.py file, if not already exists.

    models/__init__.py

    from . import new_activity_type