Enable Dark Mode!
how-to-set-default-values-with-context-in-odoo-19.jpg
By: Anupriya Ashok

How to Set Default Values with Context in Odoo 19

Technical Odoo 19 Odoo Enterprises Odoo Community

In Odoo 19, default values with context enable you to automatically fill in form fields according to particular circumstances, user actions, or external factors. By pre-filling fields with pertinent data based on the current context—such as the active user, company, date, or related records—this feature facilitates data entry.

What Are Default Values with Context in Odoo 19?

When new records are created, fields are automatically assigned default values with context, which are predefined values. Context-based defaults, in contrast to static default values, are dynamic and alter according to the environment or current circumstances. You can use the context, a Python dictionary that stores data throughout the program, to set clever default values.

1. Model Field Default 

from odoo import models, fields
class SaleOrder(models.Model):
   _inherit = 'sale.order'
   state = fields.Selection(
       default='draft'
   )

The default attribute in the model definition can be used to directly set a default value on a field. Regardless of how the form is opened, this value is automatically applied each time a new record is created. Static defaults or values that rely solely on the environment (like the current user or company) rather than action-specific context are best suited for this approach.

2. Context-Based Default Using Field default

Use when value comes directly from context

class SaleOrder(models.Model):
   _inherit = 'sale.order'
   partner_id = fields.Many2one(
       'res.partner',
       default=lambda self: self.env.context.get('default_partner_id')
   )

This reads values from the context using default_fieldname.

It is simple and efficient when only one field depends on context.

3. default_get() Method

Use when multiple fields depend on context or conditions.

from odoo import api, models
class SaleOrder(models.Model):
   _inherit = 'sale.order'
   @api.model
   def default_get(self, fields_list):
       res = super().default_get(fields_list)
       if self.env.context.get('default_partner_id'):
           res['partner_id'] = self.env.context['default_partner_id']
       return res

default_get() gives full control over how defaults are applied.

It should be used when defaults depend on logic or multiple context values.

4. XML Action Context

Use when opening a form from the menu/action

<record id="action_sale_order_simple" model="ir.actions.act_window">
   <field name="name">Sale Order</field>
   <field name="res_model">sale.order</field>
   <field name="view_mode">form</field>
   <field name="context">
       {'default_state': 'draft'}
   </field>
</record>
  • This method passes default values through an action.
  • Defaults apply only when the form is opened using this action.

5.Button Context

Use when creating records from another record

<button name="%(action_sale_order_simple)d"
       type="action"
       string="Create Sale Order"
       context="{'default_partner_id': active_id}"/>
  • Button context is commonly used to pass the current record (active_id) as a default.
  • It is ideal for creating related records like orders, invoices, or payments.

6. List View Context

Use when creating records from list views

<list string="Products"
     create="true"
     context="{'default_type': 'product'}">
   <field name="name"/>
</list>
  • Defaults are applied when the Create button is clicked from the list view.
  • Useful for setting fixed values based on the view’s purpose.

7. Python with_context()

Use in server-side code

self.env['sale.order'].with_context(
   default_partner_id=partner.id
).create({})
  • with_context() temporarily adds context values for record creation.
  • It is commonly used in automated processes, wizards, and business logic.

8. One2many Default Values

{'default_order_line': [
   (0, 0, {'name': 'Test Line'})
]}

This creates a new One2many record by default using Odoo command tuples.

Useful for pre-filling lines such as order lines or invoice lines.

9. Many2many Default Values

{'default_tag_ids': [(6, 0, [1, 2])]}
  • This assigns existing Many2many records as defaults.
  • The (6, 0, ids) command replaces existing values with the given IDs.

Best Practices

When implementing default values with context, keep these practices in mind:

Check field existence - Always verify that the field exists in fields_list before setting defaults in default_get to avoid unnecessary processing.

Use proper context keys - Prefix context keys with default_ when you want them to set field defaults automatically. Keys without this prefix won't set defaults unless you handle them explicitly.

Avoid heavy computations - Default value methods run frequently, so avoid expensive database queries or complex calculations when possible.

Consider user permissions - Ensure users have proper access rights to the records you're referencing in default values.

Handle missing data gracefully - Always check if referenced records exist before using them to set defaults.

Common Context Keys in Odoo

Here are some frequently used context keys for setting defaults:

  • default_fieldname – Sets the default value for any field
  • active_id – ID of the currently active record
  • active_ids – List of selected record IDs
  • uid – Current user ID
  • company_id – Current company ID
  • tz – User's timezone
  • lang – User's language

Default values with context in Odoo 19 are a powerful way to streamline data entry and improve user experience by automatically pre-filling fields with meaningful, situation-aware data. Whether you use static model defaults, context-driven field defaults, default_get() for complex logic, or XML and button contexts for action-specific behavior, Odoo provides flexible options to cover almost every use case. Choosing the right approach depends on where the record is created from, how dynamic the default needs to be, and whether business logic is involved. By following best practices—using proper default keys, keeping logic lightweight, and handling missing data safely—you can build clean, maintainable, and user-friendly Odoo applications that behave intelligently right from the moment a form is opened.

To read more about A Complete Guide to Default Values in Odoo 19, refer to our blog A Complete Guide to Default Values in Odoo 19.


Frequently Asked Questions

What's the difference between setting defaults in Python vs XML?

While XML context defaults only apply when accessing the form through that particular action or button, Python defaults are defined at the model level and are applicable everywhere. XML is easier to use for static values, but Python offers more control and logical capabilities.

Can I override default values set through context?

It is possible to override context defaults by either setting them in the default_get method or explicitly passing values in the create() method. Context defaults are always subordinated to explicitly passed values.

How do I set default values for One2many and Many2many fields?

For One2many and Many2many fields, use a list of tuples in the context. For example: 'default_order_line': [(0, 0, {'product_id': 1, 'quantity': 1})] where (0, 0, {...}) creates a new record with the specified values.

Why aren't my default values appearing in the form?

Common reasons include: the field isn't in the view, you're missing the default_ prefix in the context key, the default_get method isn't calling super(), or there are permission issues accessing the referenced records.

Can I use computed fields for default values?

While you can reference computed fields when setting defaults, the default value itself should be a stored value. Computed fields recalculate based on their dependencies, so setting them as defaults may not work as expected.

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
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