In Odoo, init hooks are special functions that help manage tasks during a module’s installation, update, or uninstallation. They allow developers to control specific actions at the right moment of a module's life cycle.
Here’s a quick look at the different types of init hooks:
- pre_init_hook
- Runs before the module starts installing.
- Useful for setting up checks or preparing the environment.
def pre_init_check(env):
# Verify conditions before installation
if not env['ir.module.module'].search([('name', '=', 'sale_management'), ('state', '=', 'installed')]):
raise ValueError("Sale Management must be installed.")
In your __manifest__.py:
'pre_init_hook': 'pre_init_check',
2. post_init_hook
- Runs after the module is installed.
- Commonly used to create initial records or default configurations.
def post_install_actions(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
env['student.student'].create({'name': 'First Student'})
In your __manifest__.py:
'post_init_hook': 'post_install_actions',
3. uninstall_hook
- Runs after the module is uninstalled.
- Good for cleaning up leftover data.
def clean_up(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
In your __manifest__.py:
'uninstall_hook': 'clean_up',
4. post_load
- Runs before loading any models.
- Used mainly for monkey patching (modifying core behavior).
def patch_methods():
# Custom code to override Odoo methods
In your __manifest__.py:
'post_load': 'patch_methods',