### Use setup Method in Owl Component Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/generic_components Best practice example showing the use of the setup method for component initialization instead of the constructor to ensure compatibility. ```javascript class MyComponent extends Component { setup() { // initialize component here } } ``` -------------------------------- ### Odoo Developer Tutorials: Getting Started with Application Development Source: https://www.odoo.com/documentation/16.0/developer/reference/backend/standard_modules/account/account_account_tag A series of tutorials for Odoo developers, starting from architecture overview and environment setup to creating new applications, models, fields, views, security rules, and understanding inheritance and inter-module interactions. ```Python def create_new_application(): # Placeholder for creating a new Odoo application pass def define_models_and_fields(): # Placeholder for defining Odoo models and fields pass def create_views(): # Placeholder for creating Odoo views pass ``` -------------------------------- ### Odoo Website Themes - Detailed Guide Source: https://www.odoo.com/documentation/16.0/developer/tutorials/web An in-depth guide to website themes in Odoo, covering setup, theming, layout, navigation, pages, media, building blocks, and deployment. ```APIDOC ## Website themes (Detailed) ### Description Comprehensive guide covering all aspects of Odoo website themes. ### Sections * Setup * Theming * Layout * Navigation * Pages * Media * Building blocks * Shapes * Gradients * Animations * Forms * Translations * Going live ``` -------------------------------- ### Starting Guided Tours in Odoo with Python Source: https://www.odoo.com/documentation/16.0/developer/reference/testing This snippet demonstrates how to initiate guided tours in Odoo from Python tests by inheriting from HTTPCase and using the start_tour method. It requires the Odoo test framework and a running instance; inputs include tour name and URL, outputs involve tour execution; limitations include dependency on local setup and potential issues with tour side-effects in testing. ```Python def test_your_test(self): # Optional Setup self.start_tour("/web", 'your_module.your_tour_name', login="admin") # Optional verifications ``` ```Python self.start_tour("/web", code, watch=True) ``` -------------------------------- ### Clone Odoo Petstore Module Source: https://www.odoo.com/documentation/16.0/developer/tutorials/web This command downloads the example 'petstore' Odoo module from GitHub. Ensure you have Git installed. After cloning, you need to add the 'petstore' folder to Odoo's add-ons path and install the 'oepetstore' module. ```shell git clone http://github.com/odoo/petstore ``` -------------------------------- ### Starting Odoo Server (Bash Command) Source: https://www.odoo.com/documentation/16.0/developer/tutorials/backend Invoke odoo-bin to start the Odoo server via RPC for web browser access. Requires Odoo installation. Stop by Ctrl-C twice or process kill. No specific inputs/outputs beyond server launch. ```bash odoo-bin ``` -------------------------------- ### Best practice: use setup method instead of constructor in Owl components (JavaScript) Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/owl_components Illustrates the recommended pattern of initializing component logic within the `setup` method rather than overriding the `constructor`, which is not overridable in JavaScript classes. Includes both correct and incorrect examples. ```JavaScript // correct: class MyComponent extends Component { setup() { // initialize component here } } // incorrect. Do not do that! class IncorrectComponent extends Component { props) { // initialize component here } } ``` -------------------------------- ### Odoo Owl Component Best Practice: setup() Method Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/owl_component_system Illustrates the correct and incorrect ways to initialize an Odoo Owl component. It emphasizes using the `setup()` method for initialization instead of the `constructor()`, as `setup()` is the intended and overridable method for component setup in Odoo. ```javascript // correct: class MyComponent extends Component { setup() { // initialize component here } } // incorrect. Do not do that! class IncorrectComponent extends Component { constructor(parent, props) { // initialize component here } } ``` -------------------------------- ### Install Upgrade Utils via Command Line Source: https://www.odoo.com/documentation/16.0/developer/reference/upgrades/upgrade_utils Demonstrates how to install the upgrade-utils library by cloning the repository and specifying the path during Odoo startup, or by using pip for direct installation. ```bash # Clone the repository locally $ ./odoo-bin --upgrade-path=/path/to/upgrade-util/src,/path/to/other/upgrade/script/directory [...] ``` ```bash # Install via pip $ python3 -m pip install git+https://github.com/odoo/upgrade-util@master ``` -------------------------------- ### Email Communication Setup Source: https://www.odoo.com/documentation/16.0/developer/reference/backend/assets Guides for configuring email servers, DNS records, and integrating with services like Gmail, Outlook 365, and Mailjet. ```APIDOC ## Email Communication Setup ### Description This documentation outlines the necessary steps to configure Odoo for sending and receiving emails, including setting up email servers, verifying DNS records, and integrating with various email providers using OAuth or APIs. ### Endpoints * **Send and receive emails in Odoo with an email server**: General instructions for server configuration. * **Configure DNS records to send emails in Odoo**: Essential steps for DNS setup to ensure email deliverability. * **Connect Microsoft Outlook 365 to Odoo using Azure OAuth**: Detailed guide for Outlook 365 integration. * **Connect Gmail to Odoo using Google OAuth**: Step-by-step instructions for Gmail integration. * **Mailjet API**: Information on integrating with the Mailjet API for enhanced email capabilities. * **Email issues**: Troubleshooting common problems related to email sending and receiving. ``` -------------------------------- ### Odoo How-To Guides Source: https://www.odoo.com/documentation/16.0/developer/tutorials/web A collection of practical how-to guides for common Odoo customization tasks, including CSS, fields, views, actions, web services, and reporting. ```APIDOC ## How-to guides ### Description Practical guides for performing specific tasks and customizations within Odoo. ### Topics * Write lean easy-to-maintain CSS * Customize a field * Customize a view type * Create a client action * Web Services * Multi-company Guidelines * Create customized reports * Accounting localization * Translating Modules * Connect with a device * Upgrade a customized database ``` -------------------------------- ### Implement Widget Start Method in JavaScript Source: https://www.odoo.com/documentation/16.0/developer/reference/javascript/javascript_reference These snippets illustrate best practices for implementing the start method in Odoo widgets. They show how to properly call super and handle promises to ensure $el is ready. Dependencies include web.Widget. Inputs: none, outputs: promise for lifecycle control. Limitations: Widgets must inherit from Widget and wait for start completion before accessing $el. ```javascript var Widget = require('web.Widget'); var AlmostCorrectWidget = Widget.extend({ start: function () { this.$el.hasClass(....) // in theory, $el is already set, but you don't know what the parent will do with it, better call super first return this._super.apply(arguments); }, }); ``` ```javascript var Widget = require('web.Widget'); var IncorrectWidget = Widget.extend({ start: function () { this._super.apply(arguments); // the parent promise is lost, nobody will wait for the start of this widget this.$el.hasClass(....) }, }); ``` ```javascript var Widget = require('web.Widget'); var CorrectWidget = Widget.extend({ start: function () { var self = this; return this._super.apply(arguments).then(function() { self.$el.hasClass(....) // this works, no promise is lost and the code executes in a controlled order: first super, then our code. }); }, }); ``` -------------------------------- ### Clone Odoo Petstore Module - Bash Source: https://www.odoo.com/documentation/16.0/developer/howtos/web This bash command clones the petstore example module repository from GitHub. It requires Git to be installed and runs in the terminal, creating a local petstore folder. No dependencies beyond Git are needed, and it prepares the module for addition to Odoo's addons path. ```bash $ git clone http://github.com/odoo/petstore ``` -------------------------------- ### Developer Tutorials and Guides Source: https://www.odoo.com/documentation/16.0/developer/reference/backend/assets A collection of tutorials and how-to guides for Odoo developers, covering core concepts, framework usage, and best practices. ```APIDOC ## Developer Tutorials and Guides ### Description This comprehensive section offers a range of tutorials and practical guides designed to assist developers in mastering Odoo development, from initial setup to advanced customization and framework utilization. ### Endpoints * **Tutorials**: * **Getting started**: * **Chapter 1: Architecture Overview**: Understanding Odoo's core architecture. * **Chapter 2: Development environment setup**: Instructions for setting up a local development environment. * **Chapter 3: A New Application**: Guide to creating a basic Odoo application. * **Chapter 4: Models And Basic Fields**: Defining data models and fields. * **Chapter 5: Security - A Brief Introduction**: Introduction to Odoo's security model. * **Chapter 6: Finally, Some UI To Play With**: Creating user interfaces. * **Chapter 7: Basic Views**: Understanding and creating basic views. * **Chapter 8: Relations Between Models**: Establishing relationships between data models. * **Chapter 9: Computed Fields And Onchanges**: Implementing computed fields and onchange methods. * **Chapter 10: Ready For Some Action?**: Adding business logic and actions. * **Chapter 11: Constraints**: Defining data validation constraints. * **Chapter 12: Add The Sprinkles**: Enhancing the user interface and experience. * **Chapter 13: Inheritance**: Utilizing model and view inheritance. * **Chapter 14: Interact With Other Modules**: Integrating with existing Odoo modules. * **Chapter 15: A Brief History Of QWeb**: Understanding the QWeb templating engine. * **Chapter 16: The final word**: Concluding remarks and next steps. * **Discover the JS Framework**: * **Chapter 1: Owl Components**: Introduction to the Owl JavaScript component framework. * **Chapter 2: Odoo Web Framework**: Overview of Odoo's client-side web framework. * **Master the Odoo Web Framework**: * **Chapter 1: Fields and Views**: Advanced customization of fields and views. * **Chapter 2: Miscellaneous**: Other relevant topics in the web framework. * **Chapter 3: Custom kanban view**: Creating custom Kanban views. * **Chapter 4: Creating a view from scratch**: Building views without relying on standard definitions. * **Chapter 5: Testing**: Writing and running tests for web components. * **Define module data**: Managing data within Odoo modules. * **Restrict access to data**: Implementing data access restrictions. * **Safeguard your code with unit tests**: Writing unit tests for Odoo modules. * **Reuse code with mixins**: Utilizing mixins for code reusability. * **Build PDF Reports**: Creating custom PDF reports. * **Build a website theme**: * **Chapter 1 - Theming**: Introduction to website theming concepts. * **Chapter 2 - Build your website**: Steps to construct a website. * **Chapter 3 - Customisation, Part I**: Initial customization techniques. * **Chapter 4 - Customisation, Part II**: Advanced customization strategies. * **Chapter 5 - Dynamic templates**: Creating dynamic website content. * **Chapter 6 - Going live**: Deploying and launching the website theme. * **How-to guides**: * **Write lean easy-to-maintain CSS**: Best practices for CSS development. * **Customize a field**: Modifying field behavior and appearance. * **Customize a view type**: Advanced view customization. * **Create a client action**: Developing custom client-side actions. * **Web Services**: Integrating with external web services. * **Multi-company Guidelines**: Best practices for multi-company setups. * **Create customized reports**: Building tailored reports. * **Accounting localization**: Adapting accounting for different regions. * **Translating Modules**: Process for translating Odoo modules. * **Website themes**: * **Setup**: Initial setup for website theming. * **Theming**: Core theming principles. * **Layout**: Structuring website layouts. * **Navigation**: Designing website navigation. * **Pages**: Creating and managing website pages. * **Media**: Handling media assets on the website. * **Building blocks**: Using reusable website components. * **Shapes**: Applying shape elements in themes. * **Gradients**: Using gradient effects. * **Animations**: Implementing animations on the website. * **Forms**: Designing and integrating forms. ``` -------------------------------- ### Install ipdb Debugger for Python Source: https://www.odoo.com/documentation/16.0/developer/tutorials/getting_started/02_setup This command installs the `ipdb` library, a powerful interactive Python debugger. It is a prerequisite for using `ipdb` to debug your Odoo code. No specific input or output is required beyond successful installation. ```bash pip install ipdb ``` -------------------------------- ### Odoo Data Loading: Country States CSV Example Source: https://www.odoo.com/documentation/16.0/developer/howtos/rdtraining/05_securityintro Demonstrates how to load data into Odoo using a CSV file, specifying fields like 'id', 'country_id:id', 'name', and 'code'. This method is used for initial data setup and is crucial for module installation. ```csv "id","country_id:id","name","code" state_au_1,au,"Australian Capital Territory","ACT" state_au_2,au,"New South Wales","NSW" state_au_3,au,"Northern Territory","NT" state_au_4,au,"Queensland","QLD" ... ``` -------------------------------- ### SCSS Property Ordering Example Source: https://www.odoo.com/documentation/16.0/developer/reference/guidelines Illustrates the recommended property ordering in SCSS, starting from positioning and layout properties to decorative ones. It shows how to define and use scoped SCSS and CSS variables at the top, separated by an empty line. This promotes code readability and maintainability. ```scss .o_element { $-inner-gap: $border-width + $legend-margin-bottom; --element-margin: 1rem; --element-size: 3rem; @include o-position-absolute(1rem); display: block; margin: var(--element-margin); width: calc(var(--element-size) + #{$-inner-gap}); border: 0; padding: 1rem; background: blue; font-size: 1rem; filter: blur(2px); } ``` -------------------------------- ### Odoo Configuration File Example Source: https://www.odoo.com/documentation/16.0/developer/cli An example of an Odoo configuration file, demonstrating how to set database user and filter options within the '[options]' section. This file can be overridden using the '--config' command-line argument. ```ini [options] db_user=odoo dbfilter=odoo ``` -------------------------------- ### Introduction to Web Client Customization (Outdated) Source: https://www.odoo.com/documentation/16.0/developer/tutorials/web This section covers guides on creating modules for Odoo's web client. Note that this tutorial is outdated and alternative guides are recommended for website themes and business capability extensions. ```APIDOC ## Customizing the web client ### Description This guide is about creating modules for Odoo’s web client. It is important to note that this tutorial is outdated. For creating websites with Odoo, refer to the 'Build a website theme' guide. To add business capabilities or extend existing business systems of Odoo, refer to the 'Building a Module' guide. ### Prerequisites This guide assumes knowledge of: * Javascript basics and good practices * jQuery * Underscore.js It also requires an installed Odoo instance and Git. ### Related Topics * __Build a website theme * Building a Module ``` -------------------------------- ### Run Odoo unit tests with various filters Source: https://www.odoo.com/documentation/16.0/developer/tutorials/unit_tests Demonstrates different methods to execute Odoo unit tests from the command line. The first example runs all tests for a module during installation, the second executes tests from a specific file, and the third uses tags to run a single test method for precise selection. ```shell $ # run all the tests of account, and modules installed by account $ # the dependencies already installed are not tested $ # this takes some time because you need to install the modules, but at_install $ # and post_install are respected $ odoo-bin -i account --test-enable ``` ```shell $ # run all the tests in this file $ odoo-bin --test-file=addons/account/tests/test_account_move_entry.py ``` ```shell $ # test tags can help you filter quite easily $ odoo-bin --test-tags=/account:TestAccountMove.test_custom_currency_on_account_1 ``` -------------------------------- ### Odoo Test Tour: Basic Step Examples Source: https://www.odoo.com/documentation/16.0/developer/reference/addons/testing These Javascript examples illustrate different ways to define steps within an Odoo test tour. They show how to use predefined steps and custom steps with various trigger conditions. ```javascript // First step tour.stepUtils.showAppsMenuItem(), // Second step { trigger: '.o_app[data-menu-xmlid="your_module.maybe_your_module_menu_root"]', edition: 'community' // Optional }, { // Third step }, ``` ```javascript { trigger: '.js_product:has(strong:contains(Chair floor protection)) .js_add', extra_trigger: '.oe_advanced_configurator_modal', // This ensure we are in the wizard }, ``` ```javascript { trigger: 'a:contains("Add a product")', // Extra-trigger to make sure a line is added before trying to add another one extra_trigger: '.o_field_many2one[name="product_template_id"] .o_external_button', }, ``` -------------------------------- ### Start Odoo Tour in Python Tests Source: https://www.odoo.com/documentation/16.0/developer/reference/addons/testing Initiates an Odoo tour from a Python test case by inheriting from HTTPCase and calling the start_tour method. This is useful for automating tour testing and includes optional setup and verification steps. ```python def test_your_test(self): # Optional Setup self.start_tour("/web", 'your_module.your_tour_name', login="admin") # Optional verifications ``` -------------------------------- ### Odoo CLOC Command-line Usage Examples Source: https://www.odoo.com/documentation/16.0/developer/cli Demonstrates how to use the 'odoo-bin cloc' command for code analysis. It covers options for specifying the database, addons path, and specific directories for processing code. Usage examples are provided for various scenarios, including counting code in a database and from specific file paths. ```bash $ odoo-bin cloc --addons-path=addons -d my_database ``` ```bash $ odoo-bin cloc -p addons/account ``` ```bash $ odoo-bin cloc -p addons/account -p addons/sale ``` ```bash $ odoo-bin cloc -c config.conf -d my_database ``` -------------------------------- ### Odoo: Running Examples with --test-tags Source: https://www.odoo.com/documentation/16.0/developer/reference/testing Provides practical examples of using the `--test-tags` option in Odoo for common testing scenarios. This includes running tests from a specific module, excluding tests with certain tags, and combining module and tag filtering. ```bash $ odoo-bin --test-tags /sale ``` ```bash $ odoo-bin --test-tags '/sale,-slow' ``` ```bash $ odoo-bin --test-tags '-standard, slow, /stock' ``` -------------------------------- ### Launching Tours via Browser JavaScript Source: https://www.odoo.com/documentation/16.0/developer/reference/testing This code allows starting Odoo tours directly in the browser console for debugging or observation. It requires an active Odoo browser session and debug mode; input is the tour name, output is tour initiation; limitations include not supporting Python setup and potential issues with side-effects on repeated runs. ```JavaScript odoo.startTour(tour_name); ``` -------------------------------- ### Advanced Test Filtering Examples Source: https://www.odoo.com/documentation/16.0/developer/reference/addons/testing Advanced examples showing how to run tests from specific modules while excluding slow tests, or combining standard and stock module tests with custom filtering logic. ```bash $ odoo-bin --test-tags /sale ``` ```bash $ odoo-bin --test-tags '/sale,-slow' ``` ```bash $ odoo-bin --test-tags '-standard, slow, /stock' ``` -------------------------------- ### Odoo Modular Tests with Tags (Python) Source: https://www.odoo.com/documentation/16.0/developer/howtos/rdtraining/E_unittest Demonstrates how to define Odoo tests using the 'tagged' decorator to control when tests are run. 'post_install' runs after all modules are installed, while 'at_install' runs immediately after the module's installation. This helps manage test execution order and dependencies. ```python from odoo.tests.common import TransactionCase from odoo.tests import tagged # The CI will run these tests after all the modules are installed, # not right after installing the one defining it. @tagged('post_install', '-at_install') # add `post_install` and remove `at_install` class PostInstallTestCase(TransactionCase): def test_01(self): ... @tagged('at_install') # this is the default class AtInstallTestCase(TransactionCase): def test_01(self): ... ``` -------------------------------- ### Correct Widget Lifecycle: Asynchronous Start Method Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/javascript_reference Illustrates the correct way to implement the `start` method in an Odoo Widget, ensuring that asynchronous operations and parent widget lifecycle hooks are properly awaited using Promises. This prevents race conditions and ensures `$el` is ready. ```javascript var Widget = require('web.Widget'); var CorrectWidget = Widget.extend({ start: function () { var self = this; return this._super.apply(arguments).then(function() { self.$el.hasClass(....) // this works, no promise is lost and the code executes in a controlled order: first super, then our code. }); }, }); ``` -------------------------------- ### Start Odoo Server Source: https://www.odoo.com/documentation/16.0/developer/howtos/backend This command initiates the Odoo server. Ensure the full path to 'odoo-bin' is provided if it's not in your current directory. ```bash odoo-bin ``` -------------------------------- ### Events dynamic template example (id: dynamic_filter_template_event_event_*) Source: https://www.odoo.com/documentation/16.0/developer/howtos/website_themes/building_blocks Shows the required id pattern and a working QWeb template for events, including timezone context setup. The id must start with dynamic_filter_template_event_event_. ```xml ``` -------------------------------- ### Launch Odoo Server with odoo-bin Source: https://www.odoo.com/documentation/16.0/developer/howtos/rdtraining/02_setup Launches the Odoo 16.0 server using the `odoo-bin` command-line interface. Specifies the addons path and the database to use. This command is crucial for starting the Odoo development server. ```bash cd $HOME/src/odoo/ ./odoo-bin --addons-path="addons/,../enterprise/,../tutorials" -d rd-demo ``` -------------------------------- ### ActionSwiper Component Source: https://www.odoo.com/documentation/16.0/developer/reference/javascript/generic_components Documentation for the ActionSwiper Owl component, detailing its location, description, properties, and an example of extending existing components. ```APIDOC ## ActionSwiper Component ### Description Provides functionality for swipe actions, often used in lists or cards. ### Location (Details not provided in the input text) ### Props (Details not provided in the input text) ### Example: Extending existing components ```javascript // Example code for extending ActionSwiper ``` ``` -------------------------------- ### GET /ir.model Source: https://www.odoo.com/documentation/16.0/developer/reference/external_api Retrieves information about installed Odoo models. This endpoint can be used to explore the system's content or as a precondition to operations on specific models. ```APIDOC ## GET /ir.model ### Description Queries the system for installed models to explore the system's content or prepare for operations on specific models. ### Method GET ### Endpoint /ir.model ### Response #### Success Response (200) - **name** (string) - Human-readable description of the model - **model** (string) - The name of each model in the system - **state** (string) - Whether the model was generated in Python code (`base`) or by creating an `ir.model` record (`manual`) - **field_id** (array) - List of the model's fields through a `One2many` to ir.model.fields - **view_ids** (array) - `One2many` to the Views defined for the model - **access_ids** (array) - `One2many` relation to the Access Rights set on the model #### Response Example ```json [ { "name": "Custom Model", "model": "x_custom_model", "state": "manual", "field_id": [1, 2, 3], "view_ids": [4, 5], "access_ids": [6, 7] } ] ``` ``` -------------------------------- ### Create PostgreSQL Database Source: https://www.odoo.com/documentation/16.0/developer/howtos/website_themes/setup Creates a new empty PostgreSQL database using the createdb command. Requires PostgreSQL client tools installed on the system. Input is the desired database name as a placeholder. Output is a newly created database ready for imports. ```bash createdb ``` -------------------------------- ### Update Record and Invalidate Cache - Odoo ORM Example Source: https://www.odoo.com/documentation/16.0/developer/reference/addons/orm Example demonstrating updating records using SQL with a RETURNING clause to get changed IDs, then invalidating the cache for the 'state' field on these records and notifying the ORM of the modifications. This ensures data consistency and proper recomputation of dependent fields. ```python self.env.cr.execute("UPDATE model SET state=%s WHERE state=%s RETURNING id", ['new', 'old']) ids = [row[0] for row in self.env.cr.fetchall()] records = self.env['model'].browse(ids) records.invalidate_recordset(['state']) records.modified(['state']) ``` -------------------------------- ### Run Odoo Server in Shell Source: https://www.odoo.com/documentation/16.0/developer/howtos/website_themes/setup Launches the Odoo server using odoo-bin with specified command-line arguments for addons path, database filter, and modules. Requires Odoo community directory and installed dependencies. Inputs are CLI flags for configuration. Outputs a running server accessible at localhost:8069. ```bash ./odoo-bin --addons-path=../enterprise,addons --db-filter= -d --without-demo=all -i website --dev=xml ``` -------------------------------- ### Products dynamic template example (id: dynamic_filter_template_product_product_*) Source: https://www.odoo.com/documentation/16.0/developer/howtos/website_themes/building_blocks Shows the required id pattern and a working QWeb template for products, including number-of-elements controls. The id must start with dynamic_filter_template_product_product_. ```xml ``` -------------------------------- ### Define Simple Owl Component in JavaScript Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/owl_component_system Defines a basic Owl component in JavaScript, demonstrating the use of `useState` for reactive state and `xml` for inline template definition. This method is suitable for simple components or getting started. ```javascript const { useState } = owl.hooks; const { xml } = owl.tags; class MyComponent extends Component { setup() { this.state = useState({ value: 1 }); } increment() { this.state.value++; } } MyComponent.template = xml `
`; ``` -------------------------------- ### Blog posts dynamic template example (id: dynamic_filter_template_blog_post_*) Source: https://www.odoo.com/documentation/16.0/developer/howtos/website_themes/building_blocks Shows the required id pattern and a working QWeb template for blog posts. The template iterates over records, exposes each record as record, and renders into the dynamic_snippet_template placeholder. The id must start with dynamic_filter_template_blog_post_. ```xml ``` -------------------------------- ### Dictionary Operations and Clone Patterns - Python Source: https://www.odoo.com/documentation/16.0/developer/misc/other/guidelines Demonstrates proper dictionary and list creation in Python, emphasizing readability over conciseness. Shows correct patterns for creating dictionaries, updating them, and cloning data structures without using unnecessary .clone() methods. Includes bad vs good examples for better understanding. ```Python # bad new_dict = my_dict.clone() new_list = old_list.clone() # good new_dict = dict(my_dict) new_list = list(old_list) # -- creation empty dict my_dict = {} my_dict2 = dict() # -- creation with values # bad my_dict = {} my_dict['foo'] = 3 my_dict['bar'] = 4 # good my_dict = {'foo': 3, 'bar': 4} # -- update dict # bad my_dict['foo'] = 3 my_dict['bar'] = 4 my_dict['baz'] = 5 # good my_dict.update(foo=3, bar=4, baz=5) my_dict = dict(my_dict, **my_dict2) ``` -------------------------------- ### Open Custom Powerbox with Commands Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/odoo_editor Shows how to programmatically open the Odoo Editor Powerbox with a custom set of commands and categories, bypassing the default configuration. This example demonstrates opening the Powerbox with a single 'Document' command in a 'Documentation' category. ```javascript this.odooEditor.powerbox.open( [{ name: _t('Document'), category: _t('Documentation'), description: _t("Add this text to your mailing's documentation"), fontawesome: 'fa-book', priority: 1, // This is the only command in its category anyway. }], [{ name: _t('Documentation'), priority: 300, }] ); ``` -------------------------------- ### Create Service with Dependency Injection Source: https://www.odoo.com/documentation/16.0/developer/reference/javascript/framework_overview Shows how to create a long-lived service in Odoo's dependency injection system. Services can declare dependencies and are started with the required environment. The example creates a notification service that displays periodic updates. ```javascript import { registry } from "./core/registry"; const myService = { dependencies: ["notification"], start(env, { notification }) { let counter = 1; setInterval(() => { notification.add(`Tick Tock ${counter++}`); }, 5000); } }; serviceRegistry.add("myService", myService); ``` -------------------------------- ### SCSS/CSS syntax and formatting guidelines Source: https://www.odoo.com/documentation/16.0/developer/misc/other/guidelines Shows proper SCSS/CSS formatting conventions including 4-space indentation, max 80 characters per line, proper brace placement, and meaningful whitespace. Includes examples for both SCSS with variables and plain CSS. ```scss .o_foo, .o_foo_bar, .o_baz { height: $o-statusbar-height; .o_qux { height: $o-statusbar-height * 0.5; } } .o_corge { background: $o-list-footer-bg-color; } ``` ```css .o_foo, .o_foo_bar, .o_baz { height: 32px; } .o_foo .o_quux, .o_foo_bar .o_quux, .o_baz .o_qux { height: 16px; } .o_corge { background: #EAEAEA; } ``` -------------------------------- ### Define and Register a Simple Odoo Service Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/services This example demonstrates how to define a simple Odoo service that displays a notification every 5 seconds. It utilizes the `registry` to add the service and declares a dependency on the 'notification' service. The `start` method contains the core logic. ```javascript import { registry } from "@web/core/registry"; const myService = { dependencies: ["notification"], start(env, { notification }) { let counter = 1; setInterval(() => { notification.add(`Tick Tock ${counter++}`); }, 5000); } }; registry.category("services").add("myService", myService); ``` -------------------------------- ### Set up and use IPDB debugger in Python Source: https://www.odoo.com/documentation/16.0/developer/howtos/rdtraining/02_setup This snippet shows how to install the IPDB debugging library, insert a breakpoint, and use it inside an Odoo model method. It requires the ipdb package and works with any Python code. The example demonstrates copying a record while pausing execution for inspection. ```Shell pip install ipdb ``` ```Python import ipdb; ipdb.set_trace() ``` ```Python def copy(self, default=None): import ipdb; ipdb.set_trace() self.ensure_one() chosen_name = default.get('name') if default else '' new_name = chosen_name or _('%s (copy)') % self.name default = dict(default or {}, name=new_name) return super(Partner, self).copy(default) ``` -------------------------------- ### Add Custom Powerbox Command in Odoo Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/odoo_editor Demonstrates how to extend the Odoo Editor's Powerbox by adding a new 'Document' command to a custom 'Documentation' category. This example shows the proper way to modify the _getPowerboxOptions method in a module that extends web_editor's Wysiwyg class. ```javascript _getPowerboxOptions: function () { const options = this._super(); // (existing code before the return statement) options.categories.push({ name: _t('Documentation'), priority: 300, }); options.commands.push({ name: _t('Document'), category: _t('Documentation'), description: _t("Add this text to your mailing's documentation"), fontawesome: 'fa-book', priority: 1, // This is the only command in its category anyway. }); return options; } ``` -------------------------------- ### Running Odoo Tests via Command Line Source: https://www.odoo.com/documentation/16.0/developer/reference/backend/testing Examples of running Odoo tests using the `odoo-bin --test-tags` command. Shows how to select tests by tag, combine tags, exclude tags, and specify modules, classes, or functions for testing. Supports additive selection with commas and exclusion with a '-' prefix. ```bash $ odoo-bin --test-tags nice ``` ```bash $ odoo-bin --test-tags nice,standard ``` ```bash $ odoo-bin --test-tags 'standard,-slow' ``` ```bash $ odoo-bin --test-tags /stock_account ``` ```bash $ odoo-bin --test-tags .test_supplier_invoice_forwarded_by_internal_user_without_supplier ``` ```bash $ odoo-bin --test-tags /account:TestAccountIncomingSupplierInvoice.test_supplier_invoice_forwarded_by_internal_user_without_supplier ``` ```bash $ odoo-bin --test-tags /sale ``` ```bash $ odoo-bin --test-tags '/sale,-slow' ``` ```bash $ odoo-bin --test-tags '-standard, slow, /stock' ``` -------------------------------- ### Register a Notification Service in Odoo Source: https://www.odoo.com/documentation/16.0/developer/reference/javascript/services This example demonstrates how to define and register a custom service named 'myService' in the Odoo web client. This service utilizes the 'notification' dependency to display a message every 5 seconds. It showcases the service definition interface, including dependencies and the start method. ```javascript import { registry } from "@web/core/registry"; const myService = { dependencies: ["notification"], start(env, { notification }) { let counter = 1; setInterval(() => { notification.add(`Tick Tock ${counter++}`); }, 5000); } }; registry.category("services").add("myService", myService); ``` -------------------------------- ### Odoo Configuration File Example Source: https://www.odoo.com/documentation/16.0/developer/misc/other/cmdline A sample configuration file for Odoo, demonstrating how command-line options can be mapped to file settings. It specifies database user and filter settings within the [options] section. ```ini [options] db_user=odoo dbfilter=odoo ``` -------------------------------- ### Initialize Widget with Parent in Odoo JavaScript Source: https://www.odoo.com/documentation/16.0/developer/tutorials/web Explains the critical step of passing the `parent` argument to `this._super()` when overriding the `init()` method. Failure to do so will break the parent-child relationship, preventing correct widget setup and lifecycle management. The example shows the correct pattern for initializing a widget with its parent. ```javascript local.GreetingsWidget = instance.Widget.extend({ init: function(parent, name) { this._super(parent); this.name = name; }, }); ``` -------------------------------- ### Develop Custom Hook with Lifecycle Management Source: https://www.odoo.com/documentation/16.0/developer/reference/javascript/framework_overview Demonstrates creating a custom hook using Odoo's Owl framework. Hooks provide a composable way to inject features into components with proper lifecycle management. The example creates a time update hook that automatically handles setup and cleanup. ```javascript function useCurrentTime() { const state = useState({ now: new Date() }); const update = () => state.now = new Date(); let timer; onWillStart(() => timer = setInterval(update, 1000)); onWillUnmount(() => clearInterval(timer)); return state; } ``` -------------------------------- ### Website Theme Development Source: https://www.odoo.com/documentation/16.0/developer/tutorials/web Detailed guide on building and customizing website themes within Odoo, covering theming, layout, dynamic templates, and going live. ```APIDOC ## Build a website theme ### Description This guide covers the entire process of building and customizing website themes in Odoo. ### Chapters * Chapter 1 - Theming * Chapter 2 - Build your website * Chapter 3 - Customisation, Part I * Chapter 4 - Customisation, Part II * Chapter 5 - Dynamic templates * Chapter 6 - Going live ``` -------------------------------- ### Access User Context Information in Odoo Component Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/framework_overview This Odoo component example demonstrates how to access the user service and log its context information to the console. It uses the `useService` hook to get the 'user' service and then accesses the `user.context` property. This context typically includes details like `allowed_company_ids`, `lang`, and `tz`. ```javascript class MyComponent extends Component { setup() { const user = useService("user"); console.log(user.context); } } ``` -------------------------------- ### XML Naming Conventions for Odoo Views, Actions, and Menus Source: https://www.odoo.com/documentation/16.0/developer/misc/other/guidelines Provides examples of XML naming conventions for Odoo views, actions, menus, and security configurations. Includes patterns for view types, action suffixes, and menu hierarchies. ```xml model.name.view.form ... model.name.view.kanban ... Model Main Action ... Model Access Children ... ... ... ``` -------------------------------- ### Odoo Database Upgrade Command Line Help Source: https://www.odoo.com/documentation/16.0/developer/misc/api/upgrade Displays general help and main commands for the Odoo database upgrade utility when executed via the command line. This is useful for understanding available options and parameters. ```bash $ python <(curl -s https://upgrade.odoo.com/upgrade) --help ``` -------------------------------- ### Register and Implement a Custom Service in Odoo Source: https://www.odoo.com/documentation/16.0/developer/reference/frontend/framework_overview This example demonstrates registering a custom service named 'myService' in Odoo. The service depends on the 'notification' service and, upon starting, uses it to display a 'Tick Tock' message every 5 seconds. This showcases dependency injection and service lifecycle management within Odoo. ```javascript import { registry } from "./core/registry"; const myService = { dependencies: ["notification"], start(env, { notification }) { let counter = 1; setInterval(() => { notification.add(`Tick Tock ${counter++}`); }, 5000); } }; serviceRegistry.add("myService", myService); ``` -------------------------------- ### SCSS to CSS Conversion Example Source: https://www.odoo.com/documentation/16.0/developer/reference/guidelines Demonstrates the transformation of SCSS code into its equivalent CSS output. This is useful for understanding how SCSS features like variables and nesting compile down to standard CSS. It highlights SCSS's ability to simplify CSS authoring. ```scss .o_foo, .o_foo_bar, .o_baz { height: $o-statusbar-height; .o_qux { height: $o-statusbar-height * 0.5; } } .o_corge { background: $o-list-footer-bg-color; } ``` ```css .o_foo, .o_foo_bar, .o_baz { height: 32px; } .o_foo .o_quux, .o_foo_bar .o_quux, .o_baz .o_qux { height: 16px; } .o_corge { background: #EAEAEA; } ``` -------------------------------- ### Import SQL Dump into PostgreSQL Source: https://www.odoo.com/documentation/16.0/developer/howtos/website_themes/setup Imports a SQL dump file into an existing PostgreSQL database using psql. Requires psql command-line tool and a dump.sql file. Input includes database name and dump file path. Output is a populated database with imported data. ```bash psql < dump.sql ``` -------------------------------- ### Define Tour Steps with Predefined Utilities Source: https://www.odoo.com/documentation/16.0/developer/reference/backend/testing Creates tour steps using Odoo's predefined step utilities and custom step definitions. Includes examples of showing app menu items, triggering clicks on specific elements with XML IDs, and handling different editions (community/enterprise). Steps are defined as objects with trigger selectors and optional properties. ```javascript // First step tour.stepUtils.showAppsMenuItem(), // Second step { trigger: '.o_app[data-menu-xmlid="your_module.maybe_your_module_menu_root"]', edition: 'community' // Optional }, { // Third step }, ``` -------------------------------- ### Account Resequence Widget Example Source: https://www.odoo.com/documentation/16.0/developer/howtos/discover_js_framework/03_fields_and_views This snippet shows an example of using a widget within an Odoo field declaration in XML. ```xml ``` -------------------------------- ### ArchParser Class Example Source: https://www.odoo.com/documentation/16.0/developer/howtos/discover_js_framework/06_creating_view_from_scratch Illustrates a basic ArchParser class inheriting from XMLParser, used for parsing the view's architecture and extracting relevant information. ```javascript import { XMLParser } from "@web/core/utils/xml"; export class GraphArchParser extends XMLParser { parse(arch, fields) { const result = {}; this.visitXML(arch, (node) => { ... }); return result; } } ``` -------------------------------- ### get_common_columns Function Example Source: https://www.odoo.com/documentation/16.0/developer/reference/upgrades/upgrade_utils Example of obtaining common columns present in two different tables. ```python >>> get_common_columns(cr, "table1", "table2", ignore=('id',)) ``` -------------------------------- ### GET /ir.model/{model}/fields Source: https://www.odoo.com/documentation/16.0/developer/reference/external_api Gets detailed information about fields associated with a specific model. Useful for understanding the structure of custom or built-in models. ```APIDOC ## GET /ir.model/{model}/fields ### Description Retrieves field information for a specific model, including built-in fields that are automatically available on all models. ### Method GET ### Endpoint /ir.model/{model}/fields ### Path Parameters - **model** (string) - Required - The model name to get field information for ### Query Parameters - **attributes** (array) - Optional - List of field attributes to retrieve (e.g., `string`, `help`, `type`) ### Response #### Success Response (200) Returns a dictionary of fields with their properties #### Response Example ```json { "create_uid": { "type": "many2one", "string": "Created by" }, "create_date": { "type": "datetime", "string": "Created on" }, "__last_update": { "type": "datetime", "string": "Last Modified on" }, "write_uid": { "type": "many2one", "string": "Last Updated by" }, "write_date": { "type": "datetime", "string": "Last Updated on" }, "display_name": { "type": "char", "string": "Display Name" }, "id": { "type": "integer", "string": "Id" } } ``` ``` -------------------------------- ### Internet of Things (IoT) Configuration and Devices Source: https://www.odoo.com/documentation/16.0/developer/reference/backend/assets Instructions for setting up Odoo's IoT capabilities, connecting IoT boxes, and integrating various IoT devices. ```APIDOC ## Internet of Things (IoT) ### Description This section provides detailed guidance on configuring and utilizing Odoo's Internet of Things (IoT) features, including connecting IoT boxes, integrating devices, and troubleshooting common issues. ### Endpoints * **Configuration**: * **Connect an IoT box to Odoo**: Steps to establish a connection between an IoT box and Odoo. * **Use an IoT box with a PoS**: Integrating IoT boxes with the Point of Sale module. * **HTTPS certificate (IoT)**: Managing SSL certificates for secure IoT communication. * **Updating (IoT)**: Procedures for updating IoT box firmware and software. * **Troubleshooting**: Common issues and solutions for IoT connectivity. * **Connect Windows IoT Odoo**: Specific instructions for connecting Windows IoT devices. * **Devices**: * **Connect a screen**: Integrating display devices. * **Connect a measurement tool**: Connecting sensors and measurement devices. * **Connect a camera**: Setting up camera integrations. * **Connect a footswitch**: Integrating footswitch devices. * **Connect a printer**: Connecting and managing printers. * **Connect a scale**: Integrating weighing scales. ``` -------------------------------- ### Odoo Domain Filtering Examples Source: https://www.odoo.com/documentation/16.0/developer/howtos/rdtraining/07_basicviews Illustrates how to define domains for filtering records in Odoo. The first example shows a simple AND condition selecting services with a unit price greater than 1000. The second example demonstrates complex logic using OR and NOT operators with nested AND conditions. ```python [('product_type', '=', 'service'), ('unit_price', '>', 1000)] ``` ```python ['|', ('product_type', '=', 'service'), '!', '&', ('unit_price', '>=', 1000), ('unit_price', '<', 2000)] ``` -------------------------------- ### Odoo Developer Tutorials: Odoo Web Framework Source: https://www.odoo.com/documentation/16.0/developer/reference/backend/standard_modules/account/account_account_tag Tutorials focused on the Odoo JavaScript framework, covering Owl Components, the Odoo Web Framework, and master concepts like fields, views, custom kanban views, creating views from scratch, and testing. ```JavaScript import { Component, useState } from '@odoo/owl'; class MyComponent extends Component { setup() { this.state = useState({ value: 0 }); } } MyComponent.template = 'my_module.MyComponent'; ``` -------------------------------- ### QUnit Test Suite Example (Python/JavaScript) Source: https://www.odoo.com/documentation/16.0/developer/reference/testing Demonstrates a simple QUnit test suite in Python and JavaScript, using pyUtils for evaluation. It uses assert.strictEqual for checking results. ```JavaScript QUnit.module('py_utils'); QUnit.test('simple arithmetic', function (assert) { assert.expect(2); var result = pyUtils.py_eval("1 + 2"); assert.strictEqual(result, 3, "should properly evaluate sum"); result = pyUtils.py_eval("42 % 5"); assert.strictEqual(result, 2, "should properly evaluate modulo operator");}); ```