Odoo 17 Development Book - Init Hooks

Init Hooks

Hooks are functions that run before, after, or in place of existing code. Hooks, functions that are displayed as strings, are contained in the __init__ .py file of an Odoo module.

Hooks are defined within a module's __manifest .py file using the keywords listed below.

The types of hooks used in Odoo include

  1. post_init_hook
  2. pre_init_hook
  3. uninstall_hook
  4. post_load

1. post_init_hook

Post init hook functions are those that run after the module is installed. It is added with the function name inside the __init__.py file. It will generate some data. Cursors and registry are arguments that can be passed to the post init hook.

For example,

The below code generates the data for the student.student model.

from odoo import fields, models


class Student(models.Model):
    _name = "student.student"
    _description = "Student"

    name = fields.Char(string="Name", required=True)
    phone = fields.Char(string="Phone Number")
    email = fields.Char(string="Email", required=True)

We can use the post_init_hook key to register the hook in the module's __manifest__.py file.

'post_init_hook': 'create_student',

The method defined in the post_init_hook will be executed, after the module has been installed. In your __init__.py file, import the post_init_hook function and define it as shown below.

from odoo import api, SUPERUSER_ID


def create_student(cr, registry):
   env = api.Environment(cr, SUPERUSER_ID, {})
   env['student.student'].create({
       'name': 'Student 1',
       'phone': '+7865 6675 2341',
       'email': 'student1@student.com'
   })

2. Pre_init_hook

Pre Init Hooks are the hook operations that run before the installation of the module. You can define a pre_init_hook function in your manifest file, as shown below.

'pre_init_hook': '_pre_init_student',

In the module's __init__ .py file, the _pre_init_student function should be defined.

3. Uninstall_hook

This function is called immediately after the module is uninstalled. You can define a uninstall_hook function in your manifest file, as;

'uninstall_hook': 'uninstall_hook'

4.Post Load

Before any model or #data has been initialized, this can be done. You can define a post_load function in your manifest file, as shown below.

'post_load': 'post_load'
whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message