Enable Dark Mode!
a-complete-guide-to-mastering-context-in-odoo-19-for-developers.jpg
By: Muhsina Musthafa

A Complete Guide to Mastering Context in Odoo 19 for Developers

Technical Odoo 19 Odoo Enterprises Odoo Community

In Odoo 19, context remains one of the most powerful mechanisms available. Whether you are customizing views, controlling default field values, adjusting business logic, or passing parameters between UI components and server actions, the context dictionary plays a central role in shaping user behavior and system automation.

Passing Contexts to Action

Actions such as window actions, server actions, or report actions often require additional parameters to control how the user interface behaves or how the backend logic should operate. This is where context plays a fundamental role. By passing context to an action, you can influence default field values, domain filters, behavior of buttons, and even Python logic that executes when the action is triggered.

1. Adding Context to Buttons in Views

One of the most common uses is passing context through buttons inside XML views.

<button name="action_create_invoice"
        type="object"
        string="Create Invoice"
        context="{'default_move_type': 'out_invoice'}"/>

In this, when the action executes, the invoice form opens with customer invoice preselected.

2. Passing Context Inside Action Definitions (XML)

You can embed context directly in an action definition:

<record id="action_custom_form" model="ir.actions.act_window">
    <field name="name">Custom Form</field>
    <field name="res_model">custom.model</field>
    <field name="view_mode">form</field>
    <field name="context">{'default_active': True, 'create': False}</field>
</record>

In this default value for active is set to true for the new records, and creation is restricted.

Using Context in Views

In Odoo, views (form, list, kanban, search, etc.) are one of the main places where context becomes extremely powerful. By attaching context to view elements, buttons, domains, and fields, Odoo can dynamically adjust behavior.

1. Using Context with Fields

Context can also influence how fields behave in views.

<field name="partner_id" context="{'show_address': True}"/>

In this, when opening the partner selection view, Odoo includes the partner’s address inline.

2. Using Context for Domain Filters in Views

Context is often used to make domains dynamic.

<field name="team_id"
       domain="[('company_id', '=', context.get('allowed_company_id'))]"/>

Restrict visible sales teams depending on the company context.

3. Using Context in Search Views

Context is also useful for defining default search filters.

<search>
    <filter name="my_custom_filter"
            string="My Filter"
            domain="[('state', '=', context.get('default_state'))]"/>
</search>

When opening the view, the search filter automatically adapts based on context values passed from menu items or actions.

4. Using Context with Menu Items

Menu items can pass context to the view they open (via their action).

<record id="action_product_list" model="ir.actions.act_window">
    <field name="context">{'default_type': 'service'}</field>
</record>

Context in Domain

Domains are a core part of Odoo’s filtering mechanism. They control which records a user can select in a field or see in a list. While domains can be static, Odoo becomes far more powerful when context values are used inside domains to create dynamic filtering.

Using context inside domains allows you to:

  • Filter records based on currently selected values
  • Apply rules depending on user roles or the company
  • Change dropdown optioBuild more intelligent and reusable views

Dynamic domain using context:

domain="[('company_id', '=', context.get('allowed_company_id'))]"

Contexts in Reports

Reports in Odoo, whether PDF (QWeb), HTML, or XLSX, often need additional information to determine how they should be generated. These may include:

  • parameters from wizards
  • user or company info
  • language or currency settings
  • flags that control visibility of report sections

Odoo solves this using context, making reports flexible, dynamic, and reusable without duplicating templates.

1. Accessing Context in Report Python Code

class SaleOrderReport(models.AbstractModel):
    _name = 'report.my_module.report_sale_custom'
    def _get_report_values(self, docids, data=None):
        extended = self.env.context.get('extended')
        return {
            'docs': self.env['sale.order'].browse(docids),
            'extended': extended,
        }

From here, the Python class can pass these values to the QWeb template

Using Context Inside QWeb Templates

Inside the QWeb XML template, the context values are easily accessible.

<t t-if="extended">
    <h3>Extended Information</h3>
    <p>Additional report details go here.</p>
</t>

2. Passing Context from Buttons in Views

You can also pass custom flags or values from XML buttons:

<button name="%(report_sale_custom)d"
        type="action"
        context="{'extended': True}"
        string="Print Extended Report"/>

This lets the same report generate different content depending on how it was triggered.

Default Values with Context

One of the most useful features of the context dictionary in Odoo is its ability to automatically define default values for fields when a form is opened.

Using context for default values is a clean, fast, and upgrade-friendly approach to pre-fill fields, guide user actions, and build smarter workflows.

Any key in context that starts with ‘default_’ sets a default value for a field.

1. Default Values in XML Buttons

Buttons can pass default values when opening forms:

<button type="action"
        name="%(sale.action_quotations)d"
        string="New Quotation"
        context="{'default_partner_id': active_id}"/>

2. Default Values in Menu Actions

Menu items often pre-fill fields depending on workflow.

<field name="context">
    {'default_move_type': 'out_invoice'}
</field>

When users click the “Customer Invoice” menu, the invoice form automatically sets the move type to customer invoice.

3. Default Values in Python (Returning Actions)

You can set defaults dynamically in Python.

def action_new_quotation(self):
    action = self.env.ref('sale.action_quotations').read()[0]
    action['context'] = dict(
        self.env.context,
        default_team_id=self.team_id.id
    )
    return action

4. Default Values in Wizards

Wizards frequently rely on context to pre-fill fields.

<field name="date_from" context="{'default_date_from': time.strftime('%Y-01-01')}"/>

Chained Contexts

In Odoo, context isn’t just a dictionary passed around randomly—it is a continuously inherited environment that flows through actions, views, buttons, domains, wizards, reports, onchange events, and even computed fields.

This allows Odoo to carry information from one part of the workflow to another sometimes across multiple steps, without explicitly storing anything in the database.

How Chained Contexts Work

When a user opens something in Odoo:

  1. Action loads a view > passes context
  2. View loads a form or list > context merges
  3. User clicks a button > context merges
  4. Button opens wizard or report > context merges
  5. Wizard runs Python logic > context merges
  6. Report or next action reads context

Step 1 : Menu Action

context="{'default_company_id': 3}"

Step 2 : Form View Button

context="{'from_sales': True}"

Step 3 : Wizard Button

context="{'wizard_mode': 'summary'}"

At the final step, Python receives a merged context.

{
 'default_company_id': 3,
 'from_sales': True,
 'wizard_mode': 'summary',
 'lang': 'en_US',
 'tz': 'Europe/Paris',
 'uid': 5,
 ...
}

In conclusion, mastering contexts in Odoo 19 is essential for building flexible, efficient, and user-friendly solutions. By understanding how context influences views, defaults, and business logic, developers and functional consultants can precisely control system behavior without overcomplicating the codebase. When used thoughtfully, context becomes a clean and powerful way to adapt Odoo to real business needs while keeping customizations maintainable and scalable.

To read more about How to Set Default Values with Context in Odoo 19, refer to our blog How to Set Default Values with Context in Odoo 19.


Frequently Asked Questions

How is context different from domain in Odoo?

A context modifies behavior and passes additional information, while a domain filters records. Context > Controls logic (e.g., setting default values, triggering specific behaviors). Domain > Restricts which records are displayed or selected.

What is active_id and active_ids in context?

active_id - Refers the currently selected record. active_ids - Refers to multiple selected records.

Can context be passed from Python code?

Yes. In Odoo 19, you can pass context using: self.with_context(custom_flag=True)

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



0
Comments



Leave a comment



Recent Posts

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