تخطَّ إلى المحتوى
iTime Solutions

نظام أودو

كيفية إنشاء وحدة مخصصة في Odoo 20

أنشئ وحدة Odoo 20.0 تعمل فعلاً خطوة بخطوة: ملف البيان والنموذج وصلاحيات الوصول والواجهات والقائمة، ثم ثبّتها وعالج الأخطاء الشائعة.

iTime Solutions 14 دقيقة قراءة

جزء من الدليل: الدليل الشامل لتنفيذ نظام Odoo ERP للشركات المتنامية

A custom Odoo module is a Python package with a manifest, one or more models, some views and a security file. That is the whole recipe. The parts that trip people up are the file order in the manifest, the access rights (without them your menu shows nothing) and a few syntax changes between Odoo versions.

This tutorial builds a small working module, a network device register, against Odoo 20.0. It is the current stable major release as of November 2026, according to the support table in Odoo's own documentation. Everything below was checked against the 20.0 documentation and the 20.0 source code, including the new access rights format. If you are on an older release, the differences are listed near the end.

Short answer: Create a folder with __init__.py and __manifest__.py, add a model class that inherits models.Model, grant access in security/ir.access.csv, define list, form and search views plus an action and a menu in XML, list every data file in the manifest in dependency order, then install the module with -i and the Update Apps List button in developer mode.

What does a minimal Odoo module need?

Odoo's own tutorial states the minimum: a module must contain at least two files, __manifest__.py and __init__.py. The manifest's only required key is name. With just those two files the module appears in the Apps list and installs, but it does nothing.

To be useful you add four things in this order: a model (the table), access rights (who may touch it), views and an action (how people see it), and a menu (how they reach it). Skipping the second one is the classic mistake. Odoo's documentation is explicit that when no access rights are defined on a model, no users can access the data. You get a menu, click it, and see an access error or nothing at all.

If you are new to the framework, read the framework overview for beginners first, and keep the ORM guide nearby. This article is one of the pieces of the broader Odoo implementation guide, where customisation is one decision among many. Do not write a module for something a setting or Studio can do; the Studio article explains where that line sits.

Where do you put the module, and can you scaffold it?

You need a working Odoo 20.0 server (a source checkout, a package or Docker) and a directory for your own modules that is not inside Odoo's core folders. Add that directory to --addons-path (or the addons_path line in odoo.conf). If you still need a server, see installing Odoo on Ubuntu Server or deploying it with Docker.

Odoo includes a scaffold command that creates a skeleton:

./odoo-bin scaffold itime_device_register /opt/custom_addons

I'd write the files by hand the first time, for two reasons. You learn what each file is for, and the scaffold template in the 20.0 source tree still generates the older ir.model.access.csv layout with perm_read style columns, which no longer applies in 20.0. If you do scaffold, replace that security file with the one shown below.

The final layout is:

/opt/custom_addons/itime_device_register/
├── __init__.py
├── __manifest__.py
├── models/
│   ├── __init__.py
│   └── device.py
├── security/
│   └── ir.access.csv
└── views/
    ├── device_views.xml
    └── menus.xml

Use a lowercase snake_case technical name with a company prefix. It becomes the database identifier of the module and the prefix of its external IDs, and it is painful to rename once installed.

How do you write the manifest?

The manifest is a single Python dictionary in __manifest__.py. The keys below are the ones documented in the 20.0 reference for module manifests.

{
    'name': 'Network Device Register',
    'summary': 'Keep a simple register of installed network devices',
    'version': '20.0.1.0.0',
    'category': 'Services',
    'author': 'Your Company',
    'website': 'https://www.example.com',
    'license': 'LGPL-3',
    'depends': ['base'],
    'data': [
        'security/ir.access.csv',
        'views/device_views.xml',
        'views/menus.xml',
    ],
    'application': True,
    'installable': True,
}

What each key does:

  • name is the human-readable name and the only required key.
  • version follows semantic versioning. Prefixing the series (20.0.) is the convention for modules you maintain across releases.
  • depends lists modules that must load first. base is always installed, but Odoo's docs say to list it anyway so your module is updated when base is. Add mail here later if you want a chatter on the form.
  • data lists files loaded at install and update, as paths from the module root. Order matters: files load sequentially, so security first, then views and actions, then the menus that point at those actions.
  • application set to True makes the module appear under the Apps filter as a full application, with its own icon on the home screen. Leave it False for a technical add-on to an existing app.
  • license defaults to LGPL-3. State it explicitly; Odoo's list also includes OPL-1 for proprietary modules.

The two __init__.py files wire the package together. The top-level one imports the models folder, and the models folder imports each model file:

In itime_device_register/__init__.py:

from . import models

And in itime_device_register/models/__init__.py:

from . import device

Forget either import and Odoo installs the module without creating your table. No error, no model. It is a common reason for "my model does not exist".

How do you define the model?

from odoo import fields, models


class ItimeDevice(models.Model):
    _name = 'itime.device'
    _description = 'Network Device'
    _order = 'name'

    name = fields.Char(string="Device Name", required=True)
    serial_number = fields.Char(copy=False)
    location = fields.Char()
    install_date = fields.Date(default=fields.Date.context_today)
    state = fields.Selection(
        [('active', "In Service"), ('retired', "Retired")],
        default='active', required=True, copy=False,
    )
    notes = fields.Text()
    active = fields.Boolean(default=True)

    _serial_number_unique = models.Constraint(
        'UNIQUE(serial_number)',
        "This serial number is already registered.",
    )

    def action_retire(self):
        self.write({'state': 'retired'})

Walk through it. _name is the technical name and is required; it also gives the table name (itime_device). _description is a human label, and Odoo logs a warning during loading if it is missing. _order sets the default sort.

The fields are plain class attributes. name is a Char and, being required, becomes a NOT NULL column. copy=False on the serial number and the state means duplicating a record does not copy them, which is what you want for a unique serial. The default for the install date uses fields.Date.context_today, a callable that returns today's date in the user's timezone. The field named active is reserved: when it is false the record disappears from searches, which gives you archiving for free.

The uniqueness rule is declared with models.Constraint, which creates a UNIQUE constraint in PostgreSQL. This is how the 20.0 source declares table constraints in its own modules; older releases used a _sql_constraints list. A unique constraint on a nullable column is fine here because PostgreSQL treats NULL values as distinct, so devices without a serial do not collide.

action_retire is a public method called by the button in the form. Remember that any public method (one whose name does not begin with _) can be called over RPC by an authenticated user, and Odoo's security documentation warns that arguments and the record state on such methods cannot be trusted. For a state change this simple that is fine, but for anything sensitive check rights and state inside the method. More on fields and methods is in the ORM article.

How do you grant access rights in Odoo 20.0?

This is the biggest change if you learned Odoo on an older version. In 20.0 the old access control list file and record rules were merged into one model, ir.access, loaded from security/ir.access.csv. The module in the 20.0 source tree (CRM, for instance) uses exactly this header.

id,name,model_id,group_id/id,operation,domain
access_itime_device_user,itime.device user,itime.device,base.group_user,cru,
access_itime_device_admin,itime.device admin,itime.device,base.group_system,crud,

The columns are id (an external identifier), name, model_id (the model's _name), group_id/id (the group's external ID), operation and an optional domain. The operation value is a subsequence of the letters crud for create, read, update and delete, so cru means everything except delete. A row with a group grants permissions to that group. A row with an empty group is a restriction that applies to every user, which is how multi-company rules are written now. Be careful with those: Odoo's reference warns that several global restrictions can combine so that nobody has access.

Here ordinary internal users (base.group_user) can create, read and edit devices, and only system administrators can delete them. Access is additive across groups, so an administrator ends up with all four operations.

The file name matters. Odoo derives the target model from the CSV file name, so ir.access.csv loads into ir.access. A file named ir.model.access.csv would point at a model that no longer exists in 20.0.

If you are on Odoo 19 or older

Use security/ir.model.access.csv with this header instead, and refer to the model by its generated external ID, model_ plus the model name with each dot replaced by _:

id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_itime_device_user,itime.device user,model_itime_device,base.group_user,1,1,1,0

Record rules lived in a separate XML file on those releases. For role design in a live system, see user roles and access rights.

How do you add views, an action and a menu?

Views are records of ir.ui.view, written in XML. The root element of a table view is <list>. In releases before 18 it was <tree>, and the action's view_mode said tree,form; in 20.0 write list,form. Conditional visibility uses plain Python-like expressions in attributes such as invisible="state == 'retired'". The old attrs syntax is not accepted any more.

<?xml version="1.0" encoding="utf-8"?>
<odoo>

    <record id="itime_device_view_list" model="ir.ui.view">
        <field name="name">itime.device.list</field>
        <field name="model">itime.device</field>
        <field name="arch" type="xml">
            <list>
                <field name="name"/>
                <field name="serial_number"/>
                <field name="location"/>
                <field name="install_date"/>
                <field name="state" widget="badge"/>
            </list>
        </field>
    </record>

    <record id="itime_device_view_form" model="ir.ui.view">
        <field name="name">itime.device.form</field>
        <field name="model">itime.device</field>
        <field name="arch" type="xml">
            <form>
                <header>
                    <button name="action_retire" type="object" string="Retire"
                            invisible="state == 'retired'"/>
                    <field name="state" widget="statusbar"/>
                </header>
                <sheet>
                    <group>
                        <group>
                            <field name="name"/>
                            <field name="serial_number"/>
                        </group>
                        <group>
                            <field name="location"/>
                            <field name="install_date"/>
                            <field name="active" invisible="1"/>
                        </group>
                    </group>
                    <notebook>
                        <page string="Notes" name="notes">
                            <field name="notes"/>
                        </page>
                    </notebook>
                </sheet>
            </form>
        </field>
    </record>

    <record id="itime_device_view_search" model="ir.ui.view">
        <field name="name">itime.device.search</field>
        <field name="model">itime.device</field>
        <field name="arch" type="xml">
            <search>
                <field name="name"/>
                <field name="serial_number"/>
                <field name="location"/>
                <filter string="In Service" name="in_service" domain="[('state', '=', 'active')]"/>
                <group>
                    <filter string="Location" name="group_location" context="{'group_by': 'location'}"/>
                </group>
            </search>
        </field>
    </record>

    <record id="itime_device_action" model="ir.actions.act_window">
        <field name="name">Devices</field>
        <field name="res_model">itime.device</field>
        <field name="view_mode">list,form</field>
        <field name="context">{'search_default_in_service': 1}</field>
    </record>

</odoo>

The form uses the usual structure: a <header> holding the button and the status bar, a <sheet> with nested <group> elements for the two-column layout, and a <notebook> for tabs. The active field is included but hidden because the view must contain every field it references, and invisible="1" is the idiom for that. The search view defines which fields the search box offers, a ready-made filter and a group-by. The search_default_in_service key in the action's context switches that filter on when the screen opens. More on view types is in the XML views article.

The menu structure goes in its own file so it loads after the action it points to. Nested <menuitem> elements give you the usual three levels: the root entry in the app switcher, then the entries under it, with the leaf linked to the action. The leaf takes its label from the action unless you set name.

<?xml version="1.0" encoding="utf-8"?>
<odoo>

    <menuitem id="itime_device_menu_root" name="Device Register" sequence="50">
        <menuitem id="itime_device_menu_devices" name="Devices"
                  action="itime_device_action"/>
    </menuitem>

</odoo>

The chain to remember is Menu, then Action, then View, then Model. If the menu is missing, check the action. If the action opens an empty error, check access rights. If a field does not display, check the view.

How do you install and test it?

Restart the server so the new Python files are loaded, then install from the command line or the UI.

./odoo-bin -d mydb --addons-path=addons,/opt/custom_addons -i itime_device_register

Or enable developer mode in the UI, open Apps, click Update Apps List, remove the default Apps filter if needed, search for the module and install it. -i installs and -u upgrades; both must be paired with -d naming one database.

When you change Python code, restart and upgrade the module:

./odoo-bin -d mydb --addons-path=addons,/opt/custom_addons -u itime_device_register

Changes to views alone are quicker with --dev xml, which reloads the XML from disk on each page refresh. Data files are only loaded at install or update, so without that flag an edited view needs a -u too. Do this on a development database with a copy of production data, never first on production. For the cost of getting this wrong, read the backup and recovery guide.

Then walk through the checks: the Device Register app appears on the home screen; the Devices list opens w

أسئلة وأجوبة

لماذا تظهر القائمة لكن يظهر خطأ في الصلاحيات؟

تمنع Odoo الوصول إلى أي نموذج لا تُعرَّف له صلاحيات. أضف صفاً للنموذج في ملف الأمان وسجّل الملف في مفتاح data في ملف البيان قبل ملفات الواجهات. في Odoo 20.0 الملف هو security/ir.access.csv، وفي الإصدار 19 وما قبله هو ir.model.access.csv. ثم حدّث الوحدة ليتم تحميل الصفوف.

هل يمكن استخدام وحدات مخصصة على Odoo Online؟

لا. لا تشغّل Odoo Online شيفرة Python الخاصة بك، ويمكنك تخصيصها عبر Studio والإجراءات الآلية والإعدادات. وإن احتجت وحدات مخصصة فعلاً فاستضف النظام على Odoo.sh الذي يدعم شيفرتك عبر فروع Git، أو على خادمك الخاص مع تولّي الترقيات بنفسك.

ما الفرق بين الخيارين -i و -u عند تشغيل Odoo؟

الخيار -i يثبّت وحدة غير مثبتة بعد في قاعدة البيانات، أما -u فيحدّث وحدة مثبتة ليتم تطبيق تغييرات هيكل الجداول وملفات البيانات المعدّلة. ويجب استخدام الخيارين مع -d الذي يحدد قاعدة بيانات واحدة. وبعد تعديل النماذج أو ملفات XML أعد التشغيل بالخيار -u واسم وحدتك.

كيف أضيف حقولاً إلى نموذج موجود بدلاً من إنشاء نموذج جديد؟

أنشئ صنفاً وعيّن فيه _inherit بقيمة النموذج الموجود مثل res.partner ثم عرّف الحقول الجديدة فيه. بعد ذلك أضفها إلى الشاشة عبر واجهة موروثة: سجل واجهة يشير inherit_id فيه إلى الواجهة الأصلية ويحدد xpath أو موضع الحقل مكان الإدراج. ولا تعدّل ملفات النواة أبداً.

تابع القراءة

حدثنا عن مشروعك.

احجز معاينة مجانية للموقع واحصل على عرض واضح بالنطاق والمدة والتكلفة.