How to Implement with_context in Odoo?


What is with_context()?

with_context() is an Odoo method used to pass or modify context values dynamically during method execution.

  • It creates a new environment with updated context.

  • Context can influence how models behave, including form defaults, domain filters, or custom logic in overridden methods.


✅ Syntax

recordset.with_context(key=value)

You can chain it like:

self.env['sale.order'].with_context(lang='fr_FR')


📌 Realistic Use Cases in Odoo


1. Change Language for Report Generation

Force a report to be generated in French:


report = self.env.ref('sale.action_report_saleorder')

return report.with_context(lang='fr_FR').report_action(self)


2. Pass Flags for Custom Logic in Methods

You can pass custom flags via context and use them in overridden methods.


self.with_context(skip_validation=True).action_confirm()

Then in the overridden action_confirm method:

def action_confirm(self):

    if self.env.context.get('skip_validation'):

        _logger.info("Validation skipped by context flag.")

        return True

 return super().action_confirm()



3. Set Default Field Values in create() or Views

Use context to set default field values when opening a form view:


return {

    'type': 'ir.actions.act_window',

    'name': 'Create Invoice',

    'res_model': 'account.move',

    'view_mode': 'form',

    'context': {

        'default_partner_id': self.partner_id.id,

        'default_invoice_date': fields.Date.today(),

    },

    'target': 'new',

}


Or use with_context in create logic:

self.env['account.move'].with_context(default_partner_id=self.partner_id.id).create({})



✅ Summary Table


Use Case

Code Example

Benefit

Change report language

.with_context(lang='fr_FR')

Generate multi-language reports

Pass custom logic flags

.with_context(skip_validation=True)

Control logic without changing method APIs

Set default values in create/views

.with_context(default_field=value)

Set pre-filled values in UI or backend logic