Enable Dark Mode!
how-to-import-hook-post_init_hook()-in-odoo-19.jpg
By: Sidharth P

How to Import Hook post_init_hook() in Odoo 19

Technical Odoo 19 Odoo Enterprises Odoo Community

What is post_init_hook?

In Odoo, init hooks are special functions that run at specific stages of module installation. The post_init_hook is one of the most useful; it runs immediately after a module has been installed and initialized, giving you a clean window to seed data, run migrations, or apply one-time configurations.

Think of it as your module's "welcome setup" — the perfect place to populate default records, assign groups, or set configuration parameters without the user having to do it manually.

Why Use post_init_hook?

There are several real-world scenarios where post_init_hook comes in handy:

  • Automatically create default configuration records on install
  • Seed demo or reference data specific to your business
  • Set up initial system parameters or IR configs
  • Assign default users to specific groups or roles
  • Trigger background jobs or scheduled actions on first install

How It Works

The hook is registered in your module's __manifest__.py file using the 'post_init_hook' key. Odoo looks for a function with that name in your module's __init__.py and calls it with the Odoo environment (env) after installation completes.

Example: Auto-Create Book Categories on Install

In this example, we build a module called library_catalog that manages books. On install, we want to automatically create a set of default book genre categories so users don't start with an empty system.

Step 1: models/book_category.py

Define the model for book categories:

from odoo import fields, models

class BookCategory(models.Model):
   _name = 'library.book.category'
   _description = 'Book Category'
   name = fields.Char(string='Category Name', required=True)
   code = fields.Char(string='Code')
   active = fields.Boolean(string='Active', default=True)

Step 2: __init__.py (Module Root)

Define the post_init_hook function. This is where the seeding logic lives:

def create_default_categories(env):
   """Seed default book genre categories after module install."""
   default_categories = [
       {'name': 'Fiction', 'code': 'FIC'},
       {'name': 'Non-Fiction', 'code': 'NON'},
       {'name': 'Science', 'code': 'SCI'},
       {'name': 'Technology', 'code': 'TEC'},
       {'name': 'History', 'code': 'HIS'},
   ]
   for category in default_categories:
       existing = env['library.book.category'].search(
           [('code', '=', category['code'])], limit=1
       )
       if not existing:
           env['library.book.category'].create(category)

Notice the search before create pattern — this prevents duplicate records if the module is reinstalled or the hook is somehow triggered twice.

Step 3: __manifest__.py

Register the hook in your manifest file:

{
   'name': 'Library Catalog',
   'version': '19.0.1.0.0',
   'summary': 'Manage your book collection',
   'author': 'Your Company',
   'depends': ['base'],
   'data': [
       'security/ir.model.access.csv',
       'views/book_category_views.xml',
   ],
   'post_init_hook': 'create_default_categories',
   'installable': True,
   'application': True,
}

Result After Installation

When a user installs the library_catalog module, Odoo automatically creates five book genre categories. The system is ready to use from the first moment — no manual data entry required.

Example: Auto-Create Product on Install

Odoo's core modules frequently use post_init_hook to ship with ready-made products, configurations, or reference data. This example demonstrates how to automatically create a default product the moment your module is installed — so your users never land on a blank, unconfigured system.

__init__.py :

def post_init_hook(env):
   """Create a default demo product after module installation."""
   ProductTemplate = env['product.template']
   existing = ProductTemplate.search([('default_code', '=', 'DEMO-001')], limit=1)
   if not existing:
       ProductTemplate.create({
           'name': 'Demo Product',
           'default_code': 'DEMO-001',
           'type': 'consu',
           'list_price': 100.0,
           'standard_price': 50.0,
           'sale_ok': True,
           'purchase_ok': True,
           'description': 'This is a default demo product created on module install.',
       })

__manifest__.py :

{
   'name': 'My Custom Module',
   'version': '19.0.1.0.0',
   'depends': ['product'],
   'post_init_hook': 'post_init_hook',
   'installable': True,
}

What happens here: As soon as the module is installed, Odoo automatically creates a demo product with a sales price, cost price, and internal reference code. The search check ensures it won't duplicate if the module is reinstalled.

Key Points to Remember

  • The hook function name in __manifest__.py must exactly match the function defined in __init__.py
  • The function receives a single argument: env, the Odoo environment object
  • Always check for existing records before creating to avoid duplicates on reinstall
  • post_init_hook runs only once — at install time, not on upgrades (use post_load or uninstall_hook for other stages)
  • Keep hook logic lightweight; heavy operations should be deferred to scheduled actions

post_init_hook vs pre_init_hook

It helps to understand where post_init_hook sits in the lifecycle:

HookWhen It RunsCommon Use Case
pre_init_hookBefore module installsPre-checks, cleanup old data
post_init_hookAfter module installsSeed data, default config
uninstall_hookWhen module uninstallsRemove external references

The post_init_hook is a small but powerful feature in Odoo 19 that every module developer should have in their toolkit. It bridges the gap between installation and usability by automating the initial setup that would otherwise fall on the user. Whether you're seeding reference data, configuring system parameters, or setting up default records, this hook ensures your module delivers value from the very first launch. Used responsibly — with duplicate checks and lightweight logic — it makes your module feel polished, professional, and production-ready. Simply put, if your module needs a "first-run setup," post_init_hook is the right tool for the job.

To read more about How to Use init Hooks in Odoo 19, refer to our blog How to Use init Hooks in Odoo 19.


Frequently Asked Questions

Does post_init_hook run every time the module is upgraded?

No. It only runs once — during the initial installation of the module. If you need code to run on upgrades, use the post_migrate signal or a migration script inside the migrations/ folder.

What happens if post_init_hook throws an error?

If the hook function raises an exception, Odoo will roll back the entire module installation and display the error. Always wrap risky operations in try/except blocks to handle failures gracefully.

Can I call multiple functions from post_init_hook?

Yes. Your hook function can call as many sub-functions as needed. You register just one entry point in the manifest, but that function can orchestrate any number of setup tasks internally.

Can I use post_init_hook to set ir.config_parameter values?

Absolutely. Using env['ir.config_parameter'].sudo().set_param('your.key', 'value') inside the hook is a very common pattern for setting system configuration parameters automatically during module installation.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, KINFRA Techno Park
Kakkanchery, 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