Context in Odoo

Context is used to control what is displayed in:

This is either:

  1. Defined in a Windows Action associated with a menu option OR
  2. Passed from one view to another OR
  3. Used within a Form View to control how information is displayed

These are some of the things that can be done:

Passing a default value

For example, if you create a contact from the Customers menu option, it will be a customer. That only happens because Context is used in the Windows Action: 

Windows Action Filters

{'default_customer':1,'default_is_company': True}

It will always start with  {“default_  then the field name and value.  In this case there are two fields:

  • customer = ‘1’ (True)    
  • is_company = True 

Customer

Remember that partners include customers and suppliers (vendors), and it makes sense that if you create a partner from here it will be a customer.

  • In Odoo 12 and earlier, a partner could only be selected on a Quotation / Sales Order if it was set as a customer. You can manually select whether any partner is a customer, but having a default is useful.
  • From Odoo 13 onwards the field is called customer ranking. It is not displayed in the user interface, and any partner can be selected on a Quotation / Sales Order, but customers are displayed first.

Is a company

Partners can either be a company or an individual (which would be linked to a company). So you might have the company Walmart and individual buyers.

is_company means that you will create a partner company by default.

  • Users can change this default and create an “individual” contact (linked to a company).  
  • Note that either can be selected on a quotation / sales order.

The same syntax can be used to set defaults within Form Views.

For example, if you create a new tax in the Sales app it should be a sales tax:

<field name="taxes_id"  context="{'default_type_tax_use':'sale'}" />

As well as a constant we can use a variable value.  In the next example if you create an analytic account for a sales order it will be for the customer on the order:

<field name="analytic_account_id" context="{'default_partner_id':partner_invoice_id}" />

Note that the 2nd parameter is a field name rather than a constant.

Of course, you can have defaults for multiple fields, and in this example we default both the the customer and the sales order number (again, it’s to create an Analytic Account):

<field name="analytic_account_id" context="{'default_partner_id':partner_invoice_id,
'default_name':name}
" />

Create analytic account for sales order

Note that these are defaults, so users can make changes (though sometimes the field may be read-only or invisible, in which case they can’t).

Filters

Context can be used to set a Filter when displaying records from a table.

NoteRecord Rules and domain can also restrict what records are displayed. Both of these are ‘hard’ restrictions that a user cannot bypass.

A filter will further limit what is displayed, but the user can remove it.

For example, the “Customers” menu initially displays a list of customers, and not any other type of contact. There is no domain specified for this menu option but there is a default filter set using Context (in the slightly confusingly named “Filters” section on the Windows Action):

{'search_default_customer': 1}

Note: the customer filter is a defined in the Search View. If you need to add a new filter you will have to update the search view.

This is the filter (note the ‘X’ to show that it can be removed):

If users remove the filter it will display suppliers as well (this might be useful if a contact has been setup as a supplier and should also be a customer) but of course the display is still limited by domain and Record Rules.

The same syntax can be used in Form Views to filter lists:

<field string="Customer" name="partner_id" context="{'search_default_customer':1}" />

This means that the “Customer” filter will be applied (as above).

However, in most cases domain will be used because it doesn’t make sense to allow anything other than a customer to be selected – and filter without domain would allow a supplier or other contact to be selected.

Group By

Context can be used to group records in a List View (primarily for menus and user-defined filters). This is the syntax:

 {'group_by': ['date_invoice:month', 'user_id']} 

Expand

'expand': 1

Expand a grouped list

Sort order

This allows the initial sort order to be set for a List View or Kanban View

Context (in Windows Action)

{'show_sale': True, 'search_default_order_confirmed': 1}

XML syntax for sorting (for reference – does not use Context):

<tree default_order="date desc">
<field name="date"/>
(other fields)
</tree>

Display inactive records

As standard, Odoo will only display active records from a table, but it’s possible to override this.

We can see this in the menu option for Currencies. This is the Windows Action for Accounting / Configuration / Currencies:

The important part is the Context Value:

{'active_test': False, 'search_default_active': 1}

Note that this also applies a filter (using search_default) so that initially only active currencies are displayed:

Filter ON

Remove the filter to also display inactive records

  • It’s easy to see which currencies are inactive because they appear after the active currencies and in a grey font:
Filter OFF and inactive currencies displayed

This is because Odoo comes with all currencies already setup and you should activate rather than create.

This technique can also be used in XML on a one2many-field (but it’s not common)

<field name="<field_name>" context="{'active_test': False}"/>

It’s used for currency selection, and also on the Product Template for a service item (if Project Management is installed):

<field name="project_template_id" context="{'active_test': False}"/> 

Allow force delete

It is possible to override the Odoo validation by adding 'force_delete:True but this is not recommended!

Record Selection

This is very similar to what can be done with domain.

For example, on the Contacts Form View, you only want to be able to choose states for the selected country (e.g. United States).  This is the syntax:

<field name="state_id" context="{'country_id': country_id}"/> 

This is the result:

However, it’s easier to use domain for this, and that is what you will usually find in Odoo.  

Display product names without codes

As standard, Odoo displays product codes and names together, something like this:

[FURN_6666] Acoustic Bloc Screen

If you want to display the product name (description) only, you can use context in the Windows action (tested in Odoo 17):

 {'display_default_code': False}

This doesn’t work everywhere, so you would need to check the function you want to modify!

Set language

As standard, a user selects a language and Odoo should display everything in the chosen language (though you will have to check the translation and ensure that anything you add has been translated).

It’s also possible to select a language using context. This might be useful if a user primarily uses one language but also has to check information in other languages and doesn’t want to switch their language preference every time.

The syntax is as follows (using French as an example):

{'lang': 'fr_FR'}

In the XML, it will look something like this:

<xpath expr="//field[@name='order_line']" position="attributes">
    <attribute name="context">{'lang': 'fr_FR'}</attribute>
</xpath>

OR

<page string="Order Lines" name="order_lines">
  <field name="order_line"
    widget="section_and_note_one2many"
    mode="tree,kanban"
    context="{'lang': 'fr_FR'}">

23 thoughts on “Context in Odoo

  1. Can it be used to display additional information in many2one, when selecting?
    e.g., I have custom model, which has name and id.
    I add this field onto a Contact form. When searched, it’s only possible to search by name, not id.

    Maybe you can guide me into a direction on how to see and search by both (name and id)?

    Like

    1. I don’t think this can be done by using context, but take a look at products: you can search by the product Name or the Internal Reference

      Like

  2. how can I pass a value in view to the context
    like this

    type=”object” name=”open_related_model”
    context=”{‘target_state’:value}”>

    and tried this also

    type=”object” name=”open_related_model” t-att-context=”{‘got_state’: value}”

    didn’t work for both

    Like

  3. Would it be possible through the Record Selection to select only Shipping Addresses from the selected customer’s commercial partner?

    Example for SO
    Customer: Deco Addict, Addison Olson
    Then Shipping Address field would only show the Delivery Addresses for Deco Addict.

    I added the [,’commercial_partner_id’:partner_id.commercial_partner_id] part to this line:

    But this just results in an error when trying to select the Shipping Address. Is it possible to fetch related fields or am I just doing it wrong?

    Like

  4. For the example context of {‘group_by’: [‘date_invoice:month’, ‘user_id’]}
    Is it possible to pass this in as a search default? This way, it will appear as a token in the search bar.

    Like

  5. Hello ! Thank you very much for this great website full of clear and useful explanations!

    I have an issue I can’t fin a solution for.

    I have added through Studio a field Analytic Account by Default in the header of the purchase.order.from.

    Odoo created at studio customized view.

    If I try to define in this studio customized view the fact that by default, the analytic_account_id at the order line level should be the analytic account by defaut define on the purchase.order.form header.

    So that for each line I add in the purchase order by defauft the analytic_account_id will be the analytic_account_id defined in the Analytic Account by Default in the header of the purchase.order.from.

    Here is what I have in my studio customized view (inherited view = purchase.order.form):

    {“no_create”:true}

    When I try to add the following line after line {“no_create”:true}

    {“default_account_analytic_id”: x_studio_analytic_account_po_header}

    Odoo tells me that x_studio_analytic_account_po_header is missing in the view

    Thanks for your ideas about what is the issue here.

    Kevin

    Like

      1. Hello Chris, Thanks for your fast answer. Indeed now I do not have the message telling me the field is missing in the view. However… the analytic account in the header does not default on the order lines… Do not really understand why.

        Like

  6. Hi Chris,
    Is it possible to pass the a date range in the context field?
    For instance {‘default_x_daterange’:}

    Like

  7. Hi,
    I have a question.

    It is possible to pass many2many data through context, to fill another many2many with default values?

    Like

  8. Hi! thank you for sharing. I’m new with Odoo and still learning how to customize it with Studio.
    I have a question. I added a many2one field to a form view to select the bank account. Is it possible to show the Account Name instead the account number in the list? If yes, how can I do it?
    Thank you in advance!!

    Like

  9. Hi Chris,

    I’m trying to update the product search view to group by the vendor and I’ve used the seller_ids in context but it doesn’t work! I wish if you could help.

    Thank you

    Like

  10. can we somehow pass the conditional context, like eg. i’ve made custom search filters for day of week and its working fine under Filters > Monday eg. it filters all customers with day of week set to Monday. Now what i am looking forward is that whenever the view is opened, it should pass default filter for the current day of week, i.e. if its Monday today, then filter for Monday to be selected.

    Thanks in advance. would much appreciate any assistance.

    Like

  11. Expanding groups only works with odoo +14, correct? There’s a web groupby expand module but it only provides one with a button for the user to click. I’d like to show a treeview already expanded by default. Any idea how I can get this done? I’m working with odoo 10. Thanks in advance.

    Like

  12. I have three tables Characters,Traits and Character Traits. The Traits table is pre-populated with all the possible traits a character could have, however, those traits come in many different categories.

    I have a bunch of one2many fields on the Characters table with domains limiting them to those specific categories. So the Character Skills field only displays the ‘skill’ Traits from the Character Traits table.

    Problem is that when you go to add a new Skill to the Character Traits table it shows ALL of the Traits as options, not just the Traits with Type=Skill.

    I feel like this should be exceedingly simple, but I can’t seem to figure it out. (I am using Odoo Studio, so I pretty much have to do it via XML or the sections I can access via Debug Settings.)

    Can I define an embedded search view inside a one2many field on a form? Or is there a way to directly limit the suggested values dropdown?

    Like

    1. You just need to use Domain – in Studio it will appear on the left-hand panel and it will let you setup the search. If you need to do it directly in XML, there’s an example here: Domains in Odoo

      Like

      1. I feel like I’m missing something, because I have tried to do so via domain, and while that works wonderfully when it comes to limiting which related records are shown on the one-to-many field, it doesn’t appear to have any impact on record creation. And I’m not sure where in the left-hand panel I’m supposed to be looking.

        Model: Characters (x_characters)
        Fields:
        Skills (x_base_attr_skills) – one2many – Related Model: x_characterpowerattributes, Relation Field: x_characters_id, Domain: [(‘x_attributetype’,’=’,’Skill’)]
        Merits (x_human_attr_merits) – one2many – Related Model: x_characterpowerattributes, Relation Field: x_characters_id, Domain: [(‘x_attributetype’,’=’,’merit’)]

        Model: Character Power Attributes (x_characterpowerattributes)
        Fields:
        Attribute (x_attribute) – many2one – Related Model: x_attr
        Attribute Type (x_attributetype) – selection – Related Field: x_attribute.x_type
        Character ID (x_characters_id) – many2one – Related Model: x_characters

        Model: Attributes (x_attr)
        Fields:
        Attribute (x_name) – char
        Attribute Type (x_type) – selection

        XML – Version 1

        XML – Version 2

        Neither version works or behaves any differently.

        Like

  13. Your site has been wonderful in helping me with Odoo … one related question. How can we figure out exactly what is available in the current context in any given view? There must be something obvious that I’m missing (I’m specifically trying to pull in the current user’s team_id)

    Like

Leave a comment