Enable Dark Mode!
how-to-use-context-in-reports-in-odoo-19.jpg
By: Hafsana CA

How to use Context in Reports in Odoo 19

Technical Odoo 19 Reporting

Reports are widely used in Odoo 19 for various purposes like invoices, quotes, stock levels, accounting files, and more. In many situations, when a report is generated in real-time, its working should vary depending on various factors such as the current user, language preference, company being processed, etc. This can be achieved by using context. Context is an option that lets you pass temporary data dynamically without saving anything to the database.

In this blog, we will discuss how we can utilize context for report generation in Odoo 19 reports, how custom values can be passed to reports, and then how these values are accessed within Python methods and qweb templates with the help of real-life examples.

Context in Reports

The context in Odoo 19 is the dictionary that stores transient data between operations. It can be extensively used among models, actions, views, and reports. While working with reports, context is an approach that allows developers to send some additional data into the reports, avoiding adding extra fields to the model.

It is vital to know some of the reasons why context may be used in reports before going into report customization.  Among the practical examples of such use cases are the following:

  • Sending the ID of the active record into the report
  • Adding some custom filters to the report
  • Displaying the reports in a chosen language
  • Displaying different content depending on the user role
  • Adding date ranges to the report
  • Managing the report behavior with button wizard actions

It is time to look at the way context works in reports in Odoo 19.

Passing the Context to a Report Action

In most cases, context is passed while calling the report action from Python. The with_context() method is commonly used for this purpose.

from odoo import models
class SaleOrder(models.Model):
   _inherit = 'sale.order'
   def action_print_custom_report(self):
       return self.env.ref(
           'custom_report.action_custom_sale_report'
       ).with_context(
           customer_note='Priority Customer',
           print_discount=True
       ).report_action(self)

In the above example:

  • customer_note is a custom context value
  • print_discount is a Boolean value passed into the report
  • with_context() temporarily adds these values during report generation

This approach is useful because the values exist only during execution and do not affect the database structure.

Accessing the Context within the Report Model

After passing the context, we access the context within the report’s Python class using self.env.context.

from odoo import api, models
class CustomSaleReport(models.AbstractModel):
    _name = 'report.custom_report.sale_report_template'
    @api.model
    def _get_report_values(self, docids, data=None):
        docs = self.env['sale.order'].browse(docids)
        customer_note = self.env.context.get('customer_note')
        print_discount = self.env.context.get('print_discount')
        return {
            'docs': docs,
            'customer_note': customer_note,
            'print_discount': print_discount,
        }

In the above code block, the context values have been accessed through the get() method. This is believed to be a safer way since there will be no errors even if the key is absent.

The returned value can now be used within the QWeb template.

Using Context Values Inside QWeb Reports

Once the values are passed into _get_report_values(), they become available in the report template.

<t t-if="customer_note">
   <p>
       <strong>Note:</strong>
       <t t-esc="customer_note"/>
   </p>
</t>
<t t-if="print_discount">
   <p>Discount details are included in this report.</p>
</t>

In the current case:

  • t-if determines whether there is such a value at all
  • t-esc shows this value in the report without problems
  • Depending on the context, the report contents are dynamically modified

As a result, the report is not repeated.

Using Context for Multi-Language Reports

Handling language is one of the most common ways to use context in reports. This feature is provided automatically by Odoo through its context management.

def action_print_invoice(self):
    return self.env.ref(
        'account.account_invoices'
    ).with_context(
        lang=self.partner_id.lang
    ).report_action(self)

In this case, the report language will depend on the customer's language that was set up in the partner form.

This is highly beneficial for businesses dealing with international customers, as the report would automatically show up in different languages.

Passing Context from XML Buttons

Context can also be passed directly from XML buttons.

<button name="action_print_custom_report"
       type="object"
       string="Print Report"
       context="{'print_discount': True}"/>

This method is simple and useful when only small contextual values are needed from the user interface.

However, for complex logic, handling context inside Python methods is usually cleaner and easier to maintain.

Things to Note When Using Context

As useful as context is, one needs to exercise caution when using it. Misusing context will make debugging in large modules challenging.

It is always good to practice:

  • Using meaningful context key names
  • Not putting too much data in context
  • Avoiding context as an alternative to database fields
  • Using context.get() always instead of accessing keys directly
  • Practicing restraint in the use of context

This will make the code clean enough for anyone else who reads it.

The Importance of Context in Odoo Reports

When developing ERPs, many developers would need to develop various report templates to achieve minor differences in the generated documents. With Odoo, context helps avoid the need for doing that since one report will have different behavior depending on the input provided during its execution.

This saves time, prevents code redundancy, and provides flexibility. This is especially important in a business environment with large numbers of reports that keep changing depending on customers, regions, departments, or workflows.

Incorporating the use of context in the creation of Odoo 19 Reports is an efficient method for creating report behaviors that can change dynamically without necessarily introducing new fields and/or duplication of template files. This is because temporary values passed using with_context() enable the developer to have control over how their report will be generated, depending on various business needs.

If you are developing Sales Reports, Invoices, Inventory reports, or even custom reports in PDF formats, it is important to appreciate how to utilize context effectively. This makes your life as a developer easier since you can scale your code across Odoo implementations with ease.

To read more about A Complete Guide to Mastering Context in Odoo 19 for Developers, refer to our blog A Complete Guide to Mastering Context in Odoo 19 for Developers.


Frequently Asked Questions

What is the definition of context in Odoo 19?

Context is a temporary dict that passes additional data during the process from model to view to action and even to reports.

For what purpose is context applied in reports?

To pass dynamic values to reports without writing them in the database, so we can create different report behavior depending on some condition (language, filter, etc.)

Is there any way to use the context variable in Python code?

self.env.context.get('key_name') get() is preferable to be used because it won't raise error in case of non-existence key name.

Is it possible to pass variables from context inside QWeb template in a report?

Yes. All values that we have passed via _get_report_values() can be used inside QWeb template using such tags as t-if, t-esc, etc.

How does context differ from fields?

The main difference is that the field stores data permanently in the database, whereas context stores values temporarily; after that, they disappear.

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