### Install PostgreSQL on Fedora Source: https://www.odoo.com/documentation/master/administration/on_premise/packages.html Install and initialize PostgreSQL server on Fedora using dnf, then enable and start the service. ```bash $ sudo dnf install -y postgresql-server $ sudo postgresql-setup --initdb --unit postgresql $ sudo systemctl enable postgresql $ sudo systemctl start postgresql ``` -------------------------------- ### Directory Structure Example Source: https://www.odoo.com/documentation/master/developer/reference/upgrades/upgrade_utils.html Example directory structure for upgrade test files. ```text myupgrades/ └── mymodule1/ ├── 18.0.1.1.2/ │ └── pre-myupgrade.py ``` -------------------------------- ### Install Make on Linux Source: https://www.odoo.com/documentation/master/contributing/documentation.html Installs Make on Linux using apt. ```bash $ sudo apt install make -y ``` -------------------------------- ### Install modules with odoo-bin module install Source: https://www.odoo.com/documentation/master/developer/reference/cli.html Installs the specified modules immediately. The Odoo database must already be created and initialized on PostgreSQL, for example using the db init command. ```bash $ odoo-bin module install ``` -------------------------------- ### Create an example alert block Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Use the example directive to show an example. ```rst .. example:: Use this alert block to show an example. ``` -------------------------------- ### Populate CLI usage examples Source: https://www.odoo.com/documentation/master/developer/reference/backend/populate.html Examples of running the populate command with various options: scaling, fixed seed, resuming sessions, and profiling. ```bash # Run a blueprint at 10x scale using all CPU cores $ odoo-bin populate -d mydb -b project.fake_project_demo --scale 10 -j auto # Run with a fixed seed for reproducibility $ odoo-bin populate -d mydb -b my_module.my_blueprint --seed 42 # Resume the last interrupted session $ odoo-bin populate -d mydb --resume # Resume a specific session by ID $ odoo-bin populate -d mydb --resume 7 # Save profiler traces for the generated workload $ odoo-bin populate -d mydb -b project.fake_project_demo --profile ``` -------------------------------- ### Install Odoo deb package on Ubuntu Source: https://www.odoo.com/documentation/master/administration/on_premise/packages.html Install the downloaded Odoo deb package as root. This installs Odoo as a service, creates the PostgreSQL user, and starts the server. ```bash # apt update # apt install ``` -------------------------------- ### Get test database from demo.odoo.com/start Source: https://www.odoo.com/documentation/master/developer/reference/external_rpc_api.html Requests a test database from https://demo.odoo.com/start. The returned map contains the host, database, user, and password needed for subsequent API calls. The PHP example requires the Ripcord library with XML-RPC and OpenSSL extensions enabled; the Java example uses the Apache XML-RPC library and omits imports; the Go example uses the github.com/kolo/xmlrpc library and omits imports. ```python import xmlrpc.client info = xmlrpc.client.ServerProxy('https://demo.odoo.com/start').start() url, db, username, password = info['host'], info['database'], info['user'], info['password'] ``` ```ruby require "xmlrpc/client" info = XMLRPC::Client.new2('https://demo.odoo.com/start').call('start') url, db, username, password = info['host'], info['database'], info['user'], info['password'] ``` ```php require_once('ripcord.php'); $info = ripcord::client('https://demo.odoo.com/start')->start(); list($url, $db, $username, $password) = array($info['host'], $info['database'], $info['user'], $info['password']); ``` ```java final XmlRpcClient client = new XmlRpcClient(); final XmlRpcClientConfigImpl start_config = new XmlRpcClientConfigImpl(); start_config.setServerURL(new URL("https://demo.odoo.com/start")); final Map info = (Map)client.execute( start_config, "start", emptyList()); final String url = info.get("host"), db = info.get("database"), username = info.get("user"), password = info.get("password"); ``` ```go client, err := xmlrpc.NewClient("https://demo.odoo.com/start", nil) if err != nil { log.Fatal(err) } info := map[string]string{} client.Call("start", nil, &info) url = info["host"].(string) db = info["database"].(string) username = info["user"].(string) password = info["password"].(string) ``` -------------------------------- ### Clone the petstore example module Source: https://www.odoo.com/documentation/master/developer/tutorials/web.html Clones the example Odoo module from the public repository. After cloning, add the resulting 'petstore' folder to Odoo's addons path, create a new database, and install the 'oepetstore' module. ```shell $ git clone http://github.com/odoo/petstore ``` -------------------------------- ### Install Odoo rpm package on Fedora Source: https://www.odoo.com/documentation/master/administration/on_premise/packages.html Install the downloaded Odoo rpm package using dnf localinstall, then enable and start the service. ```bash $ sudo dnf localinstall odoo_master.latest.noarch.rpm $ sudo systemctl enable odoo $ sudo systemctl start odoo ``` -------------------------------- ### Use rpc function to call a controller Source: https://www.odoo.com/documentation/master/developer/tutorials/discover_js_framework/02_build_a_dashboard.html Shows how to import and use the rpc function to call a controller route. The example includes a setup method with onWillStart that performs an async rpc call to '/my/controller' with parameters. ```javascript import { rpc } from "@web/core/network/rpc"; // ... setup() { onWillStart(async () => { const result = await rpc("/my/controller", {a: 1, b: 2}); }) // ... } ``` -------------------------------- ### Go example: create custom model and field Source: https://www.odoo.com/documentation/master/developer/reference/external_rpc_api.html Go example using Call and execute_kw to create a custom model and field, then create and read a record. Uses state='manual'. ```go var id int64 if err := models.Call("execute_kw", []any{ db, uid, password, "ir.model", "create", []map[string]string{ { "name": "Custom Model", "model": "x_custom", "state": "manual", }, }, }, &id); err != nil { log.Fatal(err) } var fieldId int64 if err := models.Call("execute_kw", []any{ db, uid, password, "ir.model.fields", "create", []map[string]any{ { "model_id": id, "name": "x_name", "ttype": "char", "state": "manual", "required": true, }, }, }, &fieldId); err != nil { log.Fatal(err) } var recordId int64 if err := models.Call("execute_kw", []any{ db, uid, password, "x_custom", "create", []map[string]string{ {"x_name": "test record"}, }, }, &recordId); err != nil { log.Fatal(err) } var recordFields []map[string]any if err := models.Call("execute_kw", []any{ db, uid, password, "x_custom", "read", [][]int64{{recordId}}, }, recordFields); err != nil { log.Fatal(err) } ``` -------------------------------- ### Install Python requirements on Windows with pip Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Run in a terminal with Administrator privileges. Installs setuptools, wheel, and requirements from requirements.txt. ```batch C:\> cd \CommunityPath C:\> pip install setuptools wheel C:\> pip install -r requirements.txt ``` -------------------------------- ### Install upgrade-util via --upgrade-path, pip, or requirements.txt Source: https://www.odoo.com/documentation/master/developer/reference/upgrades/upgrade_utils.html Install the upgrade-util library by cloning the repository and prepending its src directory to the --upgrade-path option, or via pip. On Odoo.sh, add the odoo_upgrade line to requirements.txt. ```bash $ ./odoo-bin --upgrade-path=/path/to/upgrade-util/src,/path/to/other/upgrade/script/directory [...] ``` ```bash $ python3 -m pip install git+https://github.com/odoo/upgrade-util@master ``` ```text odoo_upgrade @ git+https://github.com/odoo/upgrade-util@master ``` -------------------------------- ### Tagging test cases with at_install and post_install Source: https://www.odoo.com/documentation/master/developer/tutorials/unit_tests.html Import TransactionCase and the tagged decorator. Decorate a test class with `@tagged('post_install')` for tests that should run after all modules are installed, or with `@tagged('at_install', '-post_install')` to run during the module installation. The example includes a test method placeholder. ```python from odoo.tests import tagged, TransactionCase # The CI will run these tests after all the modules are installed, # not right after installing the one defining it. @tagged('post_install') # this is the default class PostInstallTestCase(TransactionCase): def test_01(self): ... @tagged('at_install', '-post_install') # add `at_install` and remove `post_install` class AtInstallTestCase(TransactionCase): def test_01(self): ... ``` -------------------------------- ### Start a tour from a Python test Source: https://www.odoo.com/documentation/master/developer/reference/backend/testing.html Inherits from 'HTTPCase' and calls 'start_tour' to start a tour. The 'login' parameter is optional. ```python def test_your_test(self): # Optional Setup self.start_tour("/web", "your_tour_name", login="admin") # Optional verifications ``` -------------------------------- ### HTTP Service GET and POST Requests Source: https://www.odoo.com/documentation/master/developer/reference/frontend/services.html Demonstrates how to use the http service to perform GET and POST requests. ```javascript const httpService = useService("http"); const data = await httpService.get("https://something.com/posts/1"); // ... await httpService.post("https://something.com/posts/1", { title: "new title", content: "new content" }); ``` -------------------------------- ### Prepending Files Source: https://www.odoo.com/documentation/master/developer/reference/frontend/assets.html Example of prepending a file to a bundle. ```python 'web.assets_common': [ ('prepend', 'my_addon/static/src/css/bootstrap_overridden.scss'), ], ``` -------------------------------- ### PHP example: create custom model and field Source: https://www.odoo.com/documentation/master/developer/reference/external_rpc_api.html PHP equivalent of the example using execute_kw to create a custom model and field, then create and read a record. Requires state='manual'. ```php $id = $models->execute_kw($db, $uid, $password, 'ir.model', 'create', array(array( 'name' => "Custom Model", 'model' => 'x_custom', 'state' => 'manual' ))); $models->execute_kw($db, $uid, $password, 'ir.model.fields', 'create', array(array( 'model_id' => $id, 'name' => 'x_name', 'ttype' => 'char', 'state' => 'manual', 'required' => true ))); $record_id = $models->execute_kw($db, $uid, $password, 'x_custom', 'create', array(array('x_name' => "test record"))); $models->execute_kw($db, $uid, $password, 'x_custom', 'read', array(array($record_id))); ``` -------------------------------- ### Install Python dependencies Source: https://www.odoo.com/documentation/master/contributing/documentation.html Installs the Python dependencies required for the documentation using pip and the requirements.txt file. ```bash $ pip install -r requirements.txt ``` -------------------------------- ### Install PostgreSQL on Debian/Ubuntu Source: https://www.odoo.com/documentation/master/administration/on_premise/packages.html Install PostgreSQL server on Debian/Ubuntu using apt. Required before installing Odoo. ```bash $ sudo apt install postgresql -y ``` -------------------------------- ### Command markup Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Example of command markup using :command:. ```RST Run the command :command:`make clean html` to delete existing built files and build the documentation to HTML. ``` -------------------------------- ### Install PostgreSQL on Linux Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Install PostgreSQL 16.0 or above using the package manager on Linux. ```bash $ sudo apt install postgresql postgresql-client ``` -------------------------------- ### Define HomePage widget with start() method Source: https://www.odoo.com/documentation/master/developer/tutorials/web.html Defines the HomePage widget by extending instance.Widget and overriding the start() method. The start() method is called automatically when the widget is inserted into the page. This initial version only logs a message to the console. ```javascript local.HomePage = instance.Widget.extend({ start: function() { console.log("pet store home page loaded"); }, }); ``` -------------------------------- ### File markup Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Example of file markup using :file:. ```RST Create redirections using the :file:`redirects.txt` file found at the root of the repository. ``` -------------------------------- ### Example tour steps with predefined and custom steps Source: https://www.odoo.com/documentation/master/developer/reference/backend/testing.html Shows a sequence of steps: a predefined step using 'tour.stepUtils.showAppsMenuItem()', a custom step with a trigger and 'run' action, and a comment for a third step. ```javascript // First step tour.stepUtils.showAppsMenuItem(), // Second step { trigger: '.o_app[data-menu-xmlid="your_module.maybe_your_module_menu_root"]', isActive: ['community'], // Optional run: "click", }, { // Third step }, ``` -------------------------------- ### Numbered list (starting at 6) Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Example of a numbered list starting with a specific number (6) and then using autonumbering. ```reStructuredText 6. Use this format to start the numbering with a number other than one. #. The numbering is automatic from there. ``` -------------------------------- ### edit example (fill + edit) Source: https://www.odoo.com/documentation/master/developer/reference/frontend/unit_testing/hoot.html Combination of clear() and fill(): it clears the input and then fills with the given value. The example shows filling 'foo' and then editing to 'Hello World'. ```plaintext fill("foo"); // Types "foo" in the active element edit("Hello World"); // Replaces "foo" by "Hello World" ``` -------------------------------- ### Domain.toList() with context example Source: https://www.odoo.com/documentation/master/developer/reference/frontend/framework_overview.html Shows how toList() converts a domain string to a list, using the provided context object to replace free variables. The example returns [['a', '>', 3]]. ```javascript new Domain(`[('a', '>', b)]`).toList({ b:3 }); // [['a', '>', 3]] ``` -------------------------------- ### Example: Add welcome message before header Source: https://www.odoo.com/documentation/master/developer/howtos/website_themes/layout.html Example from /website_airproof/views/website_templates.xml that adds a welcome message right before the page content using an XPath expression with position='before'. ```xml ``` -------------------------------- ### Start Odoo server with odoo-bin Source: https://www.odoo.com/documentation/master/developer/tutorials/backend.html Starts the Odoo server. The server is stopped by hitting Ctrl-C twice from the terminal or by killing the corresponding OS process. ```bash odoo-bin ``` -------------------------------- ### Example of a field declaration with generator attributes Source: https://www.odoo.com/documentation/master/developer/reference/backend/populate.html Shows a `` declaration using the `scalar.integer` generator with start, end, and distribution attributes. This is the only code example on the page. ```xml ``` -------------------------------- ### start Source: https://www.odoo.com/documentation/master/developer/reference/external_rpc_api.html Creates a test database on demo.odoo.com and returns connection details (host, database, user, password). ```APIDOC ## start ### Description Creates a test database on demo.odoo.com and returns connection details (host, database, user, password). ### Method XML-RPC call ### Endpoint https://demo.odoo.com/start ### Parameters None ### Request Example ```python import xmlrpc.client info = xmlrpc.client.ServerProxy('https://demo.odoo.com/start').start() ``` ### Response #### Success Response - **host** (string) - The URL of the Odoo server. - **database** (string) - The name of the test database. - **user** (string) - The username for authentication. - **password** (string) - The password for authentication. #### Response Example ```json { "host": "https://example.odoo.com", "database": "testdb", "user": "admin", "password": "secret" } ``` ``` -------------------------------- ### Using onMounted hook in setup Source: https://www.odoo.com/documentation/master/developer/tutorials/discover_js_framework/01_owl_components.html Hook functions must be called in the setup method. onMounted executes code when the component is mounted. ```javascript setup() { onMounted(() => { // do something here }); } ``` -------------------------------- ### Install Debian/Ubuntu dependencies with debinstall.sh Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Run this script from the Odoo Community directory to install required packages. It parses the debian/control file. ```bash $ cd odoo #CommunityPath $ sudo ./setup/debinstall.sh ``` -------------------------------- ### Launch Odoo server with odoo-bin Source: https://www.odoo.com/documentation/master/developer/tutorials/setup_guide.html Starts the Odoo server with the specified add-ons path and database. Use the -d option to select the database and --addons-path to list module directories. ```bash $ cd $HOME/src/odoo/ $ ./odoo-bin --addons-path="addons/,../enterprise/,../tutorials" -d rd-demo ``` -------------------------------- ### report_with_list example Source: https://www.odoo.com/documentation/master/developer/reference/upgrades/upgrade_utils.html Example usage of report_with_list to report a list of records. It uses cr.rowcount and cr.fetchmany(20) to get data, then calls util.report_with_list with summary, data, columns, row_format, links, total, and category. ```python total = cr.rowcount data = cr.fetchmany(20) util.report_with_list( summary="The following records were altered.", data=data, columns=("id", "name", "city", "comment", "company_id", "company_name"), row_format="Partner with id {partner_link} works at company {company_link} in {city}, ({comment})", links={"company_link": ("res.company", "company_id", "company_name"), "partner_link": ("res.partner", "id", "name")}, total=total, category="Accounting" ) ``` -------------------------------- ### Appending Files Source: https://www.odoo.com/documentation/master/developer/reference/frontend/assets.html Example of appending files to a bundle. ```python 'web.assets_common': [ 'my_addon/static/src/js/**/*', ], ``` -------------------------------- ### Python example: create custom model and field Source: https://www.odoo.com/documentation/master/developer/reference/external_rpc_api.html Python example using execute_kw to create a custom model 'x_custom' and a char field 'x_name', then create and read a record. Requires state='manual' for field activation. ```python id = models.execute_kw(db, uid, password, 'ir.model', 'create', [{ 'name': "Custom Model", 'model': "x_custom", 'state': 'manual', }]) models.execute_kw(db, uid, password, 'ir.model.fields', 'create', [{ 'model_id': id, 'name': 'x_name', 'ttype': 'char', 'state': 'manual', 'required': True, }]) record_id = models.execute_kw(db, uid, password, 'x_custom', 'create', [{'x_name': "test record"}]) models.execute_kw(db, uid, password, 'x_custom', 'read', [[record_id]]) ``` -------------------------------- ### Use setup instead of constructor in Owl component Source: https://www.odoo.com/documentation/master/developer/reference/frontend/owl_components.html Owl components should use the setup method for initialization instead of the constructor, which is not overridable in JavaScript. The example shows both the correct usage and the incorrect usage to avoid. ```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 } } ``` -------------------------------- ### Subscribe to WEB_CLIENT_READY event on env.bus Source: https://www.odoo.com/documentation/master/developer/reference/frontend/framework_overview.html Shows how to listen for a global event on the env.bus. The example subscribes to the WEB_CLIENT_READY event, which is triggered when the web client has been mounted. ```javascript // for example, in some service code: env.bus.on("WEB_CLIENT_READY", null, doSomething); ``` -------------------------------- ### Correct commit message examples Source: https://www.odoo.com/documentation/master/contributing/development/git_guidelines.html Examples of correct commit messages following the Odoo Git guidelines. Each message starts with a tag and module name, followed by a meaningful header and a long description explaining the why. The examples include references to issues (Closes #22793, Fixes #22769) and a note about the purpose of the change. ```text [REF] models: use `parent_path` to implement parent_store This replaces the former modified preorder tree traversal (MPTT) with the fields `parent_left`/`parent_right`[...] [FIX] account: remove frenglish [...] Closes #22793 Fixes #22769 [FIX] website: remove unused alert div, fixes look of input-group-btn Bootstrap's CSS depends on the input-group-btn element being the first/last child of its parent. This was not the case because of the invisible and useless alert. ``` -------------------------------- ### Install Python requirements on Linux with pip Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Navigate to the Odoo Community path and install requirements from requirements.txt for the current user. ```bash $ cd /CommunityPath $ pip install -r requirements.txt ``` -------------------------------- ### scalar.integer generator example Source: https://www.odoo.com/documentation/master/developer/reference/backend/populate.html Generates a random integer between 1 and 100 for the quantity field. The start and end attributes are inclusive bounds. ```xml ``` -------------------------------- ### Initialize a database with odoo-bin db init Source: https://www.odoo.com/documentation/master/developer/reference/cli.html Initializes a new database and installs the base module. The database name is required. Use --with-demo to install demo data, --force to delete an existing database first, and --country, --language, --username, and --password to set the main company country, default language (en_US), and default admin credentials. ```shell $ odoo-bin db init ``` -------------------------------- ### Install Faker library for fake.* generators Source: https://www.odoo.com/documentation/master/developer/reference/backend/populate.html Install the Faker library using pip to unlock the `fake.*` generators in the Populate module. ```bash $ pip install -r odoo/addons/populate/requirements.txt ``` -------------------------------- ### Applying Extensions Separately (Valid Example) Source: https://www.odoo.com/documentation/master/developer/reference/frontend/patching_code.html Demonstrates the correct approach: patch the base extension first, then a new extension that does not copy from the first one. ```javascript const valid_ext2 = { method2() { super.method2(); doOtherThings(); }, }; patch(object, ext1); // first patch base extension patch(object, valid_ext2); // then the new one object.method1(); // works as expected ``` -------------------------------- ### Calendar view example Source: https://www.odoo.com/documentation/master/developer/tutorials/backend.html A calendar view that displays records as events, using the invent_date field for the start date and inventor_id for color segmentation. ```xml ``` -------------------------------- ### Including Sub-bundles Source: https://www.odoo.com/documentation/master/developer/reference/frontend/assets.html Example of including a sub-bundle. ```python 'web.assets_common': [ ('include', 'web._primary_variables'), ], ``` -------------------------------- ### Add Odoo Community repository on Fedora Source: https://www.odoo.com/documentation/master/administration/on_premise/packages.html Add the Odoo nightly repository for Fedora and install Odoo Community, then enable and start the service. ```bash $ sudo dnf config-manager --add-repo=https://nightly.odoo.com/master/nightly/rpm/odoo.repo $ sudo dnf install -y odoo $ sudo systemctl enable odoo $ sudo systemctl start odoo ``` -------------------------------- ### Source file tree example showing documentation directory structure Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Illustrates a documentation directory structure with an `import.rst`, `variants.rst`, and `prices.rst` in the `sales/products_prices/products` directory. Used to explain relative vs absolute paths. ```plaintext documentation ├── content │ └── applications │ │ └── sales │ │ │ └── sales │ │ │ │ └── products_prices │ │ │ │ │ └── products │ │ │ │ │ │ └── import.rst │ │ │ │ │ │ └── variants.rst │ │ │ │ │ └── prices.rst ``` -------------------------------- ### Example theme.scss Source: https://www.odoo.com/documentation/master/developer/howtos/website_themes/theming.html Example SCSS file that uses Bootstrap variables and Odoo functions to style a blockquote element. It demonstrates using $rounded-pill, o-color, and o-website-value. ```scss blockquote { border-radius: $rounded-pill; color: o-color('o-color-3'); font-family: o-website-value('headings-font'); } ``` -------------------------------- ### On-premise upgrade help command Source: https://www.odoo.com/documentation/master/administration/upgrade.html Displays the general help and main commands for the upgrade script. ```bash $ python <(curl -s https://upgrade.odoo.com/upgrade) --help ``` -------------------------------- ### Onboarding tour file structure Source: https://www.odoo.com/documentation/master/developer/reference/backend/testing.html Shows the required files for an onboarding tour in 'your_module': a data XML file, a JavaScript file, and the manifest. ```text your_module ├── ... ├── data | └── your_tour.xml ├── static/src/js/tours/your_tour.js └── __manifest__.py ``` -------------------------------- ### Native module import/export supported and not supported examples Source: https://www.odoo.com/documentation/master/developer/reference/frontend/javascript_modules.html Shows supported and not supported syntax for import/export in native modules. Supported: import/export with spaces before, multiline comments with import/export at line start. Not supported: import after code on same line, multiline comments with import/export not at line start. ```javascript // supported import X from "xxx"; export X; export default X; import X from "xxx"; /* * import X ... */ /* * export X */ // not supported var a= 1;import X from "xxx"; /* import X ... */ ``` -------------------------------- ### Create and use a registry Source: https://www.odoo.com/documentation/master/developer/reference/frontend/registries.html Shows how to import the Registry class, create a new registry, add a key-value pair, and retrieve it with get(). ```javascript import { Registry } from "@web/core/registry"; const myRegistry = new Registry(); myRegistry.add("hello", "odoo"); console.log(myRegistry.get("hello")); ``` -------------------------------- ### Mount the application in app.js Source: https://www.odoo.com/documentation/master/developer/howtos/standalone_owl_application.html Sets up the application by waiting for the DOM to be ready and then mounting the Root component to the document body using the mountComponent utility from @web/env. This utility handles environment creation, service startup, translation, and template access. ```javascript import { whenReady } from "@odoo/owl"; import { mountComponent } from "@web/env"; import { Root } from "./root"; whenReady(() => mountComponent(Root, document.body)); ``` -------------------------------- ### misc.counter generator example Source: https://www.odoo.com/documentation/master/developer/reference/backend/populate.html Generates an arithmetic sequence with misc.counter. start defaults to 0, step to 1, and end to None (no wrap). Compatible with integer and float fields. ```xml ``` -------------------------------- ### Replacing Files Source: https://www.odoo.com/documentation/master/developer/reference/frontend/assets.html Example of replacing an asset file. ```python 'web.assets_common': [ ('replace', 'web/static/src/js/boot.js', 'my_addon/static/src/js/boot.js'), ], ``` -------------------------------- ### Get parent widget with getParent() Source: https://www.odoo.com/documentation/master/developer/tutorials/web.html Overrides the start() method to log the parent widget's root element using getParent(). The comment shows the expected console output. ```javascript local.GreetingsWidget = instance.Widget.extend({ start: function() { console.log(this.getParent().$el ); // will print "div.oe_petstore_homepage" in the console }, }); ``` -------------------------------- ### drag example with cancel and moveTo Source: https://www.odoo.com/documentation/master/developer/reference/frontend/unit_testing/hoot.html Starts a drag sequence on the first .card element, moves the dragged card to the 4th card, then cancels the drag. The helper returns a promise that resolves to an array of events. ```plaintext const { cancel, moveTo } = await drag(".card:first"); // Starts the drag sequence moveTo(".card:eq(3)"); // Moves the dragged card to the 4th card cancel(); // Cancels the drag sequence ``` -------------------------------- ### UpgradeCase prepare and check example Source: https://www.odoo.com/documentation/master/developer/reference/upgrades/upgrade_utils.html Use this test case to verify the upgrade flow. Override `prepare` to set up data and `check` to assert expectations after the upgrade; the return value of `prepare` is persisted and passed to `check`. This type is intended only for development, not production upgrades. ```python from odoo.upgrade.testing import UpgradeCase, change_version class DeactivateBobUsers(UpgradeCase): def prepare(self): u = self.env["res.users"].create({"login": "bob", "name": "Bob"}) return u.id # will be passed to check def check(self, uid): # uid is the value returned by prepare self.env.cr.execute( "SELECT * FROM res_users WHERE id=%s AND NOT active", [uid] ) self.assertEqual(self.env.cr.rowcount, 1) ``` -------------------------------- ### Get children widgets with getChildren() Source: https://www.odoo.com/documentation/master/developer/tutorials/web.html Overrides start() to create a GreetingsWidget child, append it to the current widget's root element, and log the first child's root element using getChildren(). The comment shows the expected console output. ```javascript local.HomePage = instance.Widget.extend({ start: function() { var greeting = new local.GreetingsWidget(this); greeting.appendTo(this.$el); console.log(this.getChildren()[0].$el); // will print "div.oe_petstore_greetings" in the console }, }); ``` -------------------------------- ### Run Odoo with odoo-bin (Linux, Windows, macOS) Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Launch Odoo from the command line. The first block is for Linux, the second for Windows, and the third for macOS. Replace CommunityPath with the Odoo Community installation path and mydb with the PostgreSQL database name. On Windows, provide the PostgreSQL user and password via -r and -w. After startup, the log 'odoo.modules.loading: Modules loaded.' appears and the web interface is available at http://localhost:8069. ```bash $ cd /CommunityPath $ python3 odoo-bin --addons-path=addons -d mydb ``` ```dos C:\> cd CommunityPath/ C:\> python odoo-bin -r dbuser -w dbpassword --addons-path=addons -d mydb ``` ```bash $ cd /CommunityPath $ python3 odoo-bin --addons-path=addons -d mydb ``` -------------------------------- ### Use action service to execute an action by XML ID Source: https://www.odoo.com/documentation/master/developer/tutorials/discover_js_framework/02_build_a_dashboard.html Shows how to import and use the 'action' service in an Odoo component to execute an action by its XML ID. The example includes a setup method that assigns the service and an openSettings method that calls doAction. ```javascript import { useService } from "@web/core/utils/hooks"; ... setup() { this.action = useService("action"); } openSettings() { this.action.doAction("base_setup.action_general_configuration"); } ... ``` -------------------------------- ### Create Owl component template (your_component.xml) Source: https://www.odoo.com/documentation/master/developer/howtos/frontend_owl_components.html XML template for a simple Owl component that renders 'Hello, World!'. Place this file in /your_module/static/src/portal_component/your_component.xml. ```xml Hello, World! ``` -------------------------------- ### Restrict database access with --db-filter and update base module Source: https://www.odoo.com/documentation/master/developer/reference/cli.html Restrict access to databases whose name starts with 11, and update base module on one database: 11firstdatabase. If database 11seconddatabase doesn’t exist, the database is created and base modules is installed. ```shell $ odoo-bin --db-filter ^11.*$ --database 11firstdatabase,11seconddatabase -u base ``` -------------------------------- ### Define an Owl component in JavaScript with an inline template Source: https://www.odoo.com/documentation/master/developer/reference/frontend/owl_components.html Use this snippet to define a simple Owl component with an inline QWeb template, using useState for reactive state and t-on-click for event handling. This is useful for getting started, but in practice templates should be defined in XML files. ```javascript import { Component, xml, useState } from "@odoo/owl"; class MyComponent extends Component { static template = xml`
`; setup() { this.state = useState({ value: 1 }); } increment() { this.state.value++; } } ``` -------------------------------- ### Install a module without demo data Source: https://www.odoo.com/documentation/master/administration/odoo_sh/advanced.html Installs the 'sale' module without loading demo data and stops the server after the operation. The --without-demo=all flag prevents demo data from being loaded for all modules, and --stop-after-init shuts down the server immediately after completion. ```bash odoo-bin -i sale --without-demo=all --stop-after-init ``` -------------------------------- ### Odoo module manifest example (__manifest__.py) Source: https://www.odoo.com/documentation/master/developer/reference/backend/module.html Defines the required structure of an Odoo module manifest file. The manifest is a Python dictionary stored in __manifest__.py and declares module metadata such as name, version, dependencies, data files, and demo data. The 'data' list is always loaded at installation, while 'demo' is only loaded in demonstration mode. ```python { 'name': "A Module", 'version': '1.0', 'depends': ['base'], 'author': "Author Name", 'category': 'Category', 'description': """ Description text """, # data files always loaded at installation 'data': [ 'views/mymodule_view.xml', ], # data files containing optionally loaded demonstration data 'demo': [ 'demo/demo_data.xml', ], } ``` -------------------------------- ### Example step with async run function Source: https://www.odoo.com/documentation/master/developer/reference/backend/testing.html A step that uses an async 'run' function, which is exactly the same as 'run: "click"'. It also uses 'isActive', 'content', and 'tooltipPosition'. ```javascript { isActive: ["mobile", "enterprise"], content: "Click on Add a product link", trigger: 'a:contains("Add a product")', tooltipPosition: "bottom", async run(helpers) { //Exactly the same as run: "click" helpers.click(); } }, ``` -------------------------------- ### Register onboarding tour with web_tour.tour record Source: https://www.odoo.com/documentation/master/developer/reference/backend/testing.html Create a web_tour.tour record in XML to register an onboarding tour. The name field must match the JavaScript registry name. Sequence determines execution order (defaults to 1000), url defaults to "/odoo", and rainbow_man_message defaults to "Good job! You went through all steps of this tour." ```xml your_tour 10 Congrats, that was a great tour ``` -------------------------------- ### Create custom model and fetch fields (Go) Source: https://www.odoo.com/documentation/master/developer/reference/external_rpc_api.html Creates a custom model named 'x_custom_model' with state 'manual' and then fetches its fields. The model initially contains only built-in fields. Custom model names must start with 'x_'. ```Go var id int64 if err := models.Call("execute_kw", []any{ db, uid, password, "ir.model", "create", []map[string]string{ { "name": "Custom Model", "model": "x_custom_model", "state": "manual", }, }, }, &id); err != nil { log.Fatal(err) } recordFields := map[string]string{} if err := models.Call("execute_kw", []any{ db, uid, password, "x_custom_model", "fields_get", []any{}, map[string][]string{ "attributes": {"string", "help", "type"}, }, }, &recordFields); err != nil { log.Fatal(err) } ``` -------------------------------- ### Install rtlcss on Windows Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Install rtlcss globally using npm. After installation, add the folder containing rtlcss.cmd to the system PATH. ```batch C:\> npm install -g rtlcss ``` -------------------------------- ### CSV data file for country states Source: https://www.odoo.com/documentation/master/developer/tutorials/server_framework_101/04_securityintro.html Example CSV data file for loading country states into the res.country.state model. The id column is an external identifier, country_id:id references the country by external identifier, and name and code hold the state name and code. Data files are loaded only at module install or update, and must be declared in the __manifest__.py data list. ```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" ... ``` -------------------------------- ### Sample Odoo configuration file Source: https://www.odoo.com/documentation/master/developer/reference/cli.html Example configuration file with `[options]` section, showing `db_user` and `dbfilter` settings. The default file is `_$HOME_/.odoorc`, overridable with `--config`. ```ini [options] db_user=odoo dbfilter=odoo ``` -------------------------------- ### Utility class example Source: https://www.odoo.com/documentation/master/developer/howtos/scss_tips.html Example of a utility class definition for position-relative. ```css position-relative { position: relative !important; } ``` -------------------------------- ### Definition markup Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Example of definition markup using :dfn:. ```RST The documentation is written in RST and needs to be built (:dfn:`converted to HTML`) to display nicely. ``` -------------------------------- ### Run Odoo unit tests with odoo-bin --test-enable, --test-file, and --test-tags Source: https://www.odoo.com/documentation/master/developer/tutorials/unit_tests.html Shows the Odoo test runner options and three example invocations: install a module with tests enabled, run a specific test file, and filter tests by tags. The --test-tags spec format is documented in the help output, including the optional '-' for exclusion and the default 'standard' tag. ```shell $ odoo-bin -h Usage: odoo-bin [options] Options: --version show program's version number and exit -h, --help show this help message and exit [...] Testing Configuration: --test-file=TEST_FILE Launch a python test file. --test-enable Enable unit tests. --test-tags=TEST_TAGS Comma-separated list of specs to filter which tests to execute. Enable unit tests if set. A filter spec has the format: [-][tag][/module][:class][.method] The '-' specifies if we want to include or exclude tests matching this spec. The tag will match tags added on a class with a @tagged decorator (all Test classes have 'standard' and 'post_install' tags until explicitly removed, see the decorator documentation). '*' will match all tags. If tag is omitted on include mode, its value is 'standard'. If tag is omitted on exclude mode, its value is '*'. The module, class, and method will respectively match the module name, test class name and test method name. Example: --test-tags :TestClass.test,/test_module,external Filtering and executing the tests happens twice: right after each module installation/update and at the end of the modules loading. At each stage tests are filtered by --test-tags specs and additionally by dynamic specs 'at_install' and 'post_install' correspondingly. --screencasts=DIR Screencasts will go in DIR/{db_name}/screencasts. --screenshots=DIR Screenshots will go in DIR/{db_name}/screenshots. Defaults to /tmp/odoo_tests. $ # 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 $ # run all the tests in this file $ odoo-bin --test-file=addons/account/tests/test_account_move_entry.py $ # test tags can help you filter quite easily $ odoo-bin --test-tags=/account:TestAccountMove.test_custom_currency_on_account_1 ``` -------------------------------- ### Instantiate a class with new Source: https://www.odoo.com/documentation/master/developer/tutorials/web.html Shows how to create an instance of a class using the new operator and call its method. The output is 'hello' in the console. ```javascript var my_object = new MyClass(); my_object.say_hello(); // print "hello" in the console ``` -------------------------------- ### Icon markup Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Three examples of icon markup using :icon: and :guilabel: descriptors. ```RST The graph view is represented by the :icon:`fa-area-chart` :guilabel:`(area chart)` icon. The pivot view is represented by the :icon:`oi-view-pivot` icon. Use :icon:`os-global-filters` :guilabel:`(global filters)` in Odoo **Spreadsheet**. ``` -------------------------------- ### useAutofocus example Source: https://www.odoo.com/documentation/master/developer/reference/frontend/hooks.html Example of using the useAutofocus hook in a component and its corresponding template. ```javascript import { useAutofocus } from "@web/core/utils/hooks"; class Comp { setup() { this.inputRef = useAutofocus(); } static template = "Comp"; } ``` ```xml ``` -------------------------------- ### JSON-RPC Request and Response Examples Source: https://www.odoo.com/documentation/master/developer/reference/backend/http.html Examples of JSON-RPC requests and responses for the JsonRPCDispatcher. ```json --> {"jsonrpc": "2.0", "method": "call", "params": {"arg1": "val1" }, "id": null} <-- {"jsonrpc": "2.0", "result": { "res1": "val1" }, "id": null} ``` ```json --> {"jsonrpc": "2.0", "method": "call", "params": {"arg1": "val1" }, "id": null} ``` -------------------------------- ### Constructing a Query with Query builder Source: https://www.odoo.com/documentation/master/developer/reference/backend/orm.html Demonstrates initializing a Query object, adding a WHERE clause, and generating the SQL string. ```python query = Query(self.env['model']) query.add_where(SQL("%s > %s", query.table.some_field, 'test')) query.select() # SELECT model.id # FROM model # WHERE model.some_field > 'test' ``` -------------------------------- ### Open customers with list and form views Source: https://www.odoo.com/documentation/master/developer/reference/backend/actions.html Example of a window action dictionary that opens the res.partner model with list and form views, filtering for customers. ```json { "type": "ir.actions.act_window", "res_model": "res.partner", "views": [[False, "list"], [False, "form"]], "domain": [["customer", "=", true]], } ``` -------------------------------- ### Verbose utility-classes example Source: https://www.odoo.com/documentation/master/developer/howtos/scss_tips.html Example of verbose utility-class usage in a QWeb attribute. ```xml ``` -------------------------------- ### Install ipdb Python debugger Source: https://www.odoo.com/documentation/master/developer/tutorials/setup_guide.html Installs the ipdb library for Python debugging. ```bash pip install ipdb ``` -------------------------------- ### Odoo-bin command line with demo data Source: https://www.odoo.com/documentation/master/developer/tutorials/define_module_data.html Command line usage of odoo-bin showing the --with-demo option and an example command to create a new database with demo data. ```bash $ ./odoo-bin -h Usage: odoo-bin [options] Options: --version show program's version number and exit -h, --help show this help message and exit Common options: [...] --with-demo install demo data in new databases [...] $ ./odoo-bin --addons-path=... -d new-db -i base --with-demo ``` -------------------------------- ### Improved readability example Source: https://www.odoo.com/documentation/master/developer/howtos/scss_tips.html Example of improved readability using t-att-class and class attributes. ```xml ``` -------------------------------- ### Install Command Line Tools on macOS Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Required before installing non-Python dependencies on macOS. ```bash $ xcode-select --install ``` -------------------------------- ### Interacting with the server Source: https://www.odoo.com/documentation/master/developer/reference/frontend/unit_testing/mock_server.html Example of interacting with the mock server by creating records on the res.partner model. ```javascript const ids = MockServer.env["res.partner"].create([ { name: "foo" }, { name: "bar" }, ]); ``` -------------------------------- ### Ruby example: create custom model and field Source: https://www.odoo.com/documentation/master/developer/reference/external_rpc_api.html Ruby equivalent using execute_kw to set up a custom model and field, then create and read a record. Uses state='manual'. ```ruby id = models.execute_kw(db, uid, password, 'ir.model', 'create', [{ name: "Custom Model", model: "x_custom", state: 'manual' }]) models.execute_kw(db, uid, password, 'ir.model.fields', 'create', [{ model_id: id, name: "x_name", ttype: "char", state: "manual", required: true }]) record_id = models.execute_kw(db, uid, password, 'x_custom', 'create', [{x_name: "test record"}]) models.execute_kw(db, uid, password, 'x_custom', 'read', [[record_id]]) ``` -------------------------------- ### Example parts object for Title service Source: https://www.odoo.com/documentation/master/developer/reference/frontend/services.html An example of a parts object representing the title components. ```javascript { odoo: "Odoo", action: "Import" } ``` -------------------------------- ### Flip shape example Source: https://www.odoo.com/documentation/master/developer/howtos/website_themes/shapes.html Example of flipping a shape horizontally and vertically using the flip option. ```html
``` -------------------------------- ### Clone odoo/tutorials repository Source: https://www.odoo.com/documentation/master/developer/tutorials/setup_guide.html Clone the odoo/tutorials repository so it can be added to the addons-path alongside odoo/odoo and odoo/enterprise. Run this command after downloading the source repos. ```bash $ git clone git@github.com:odoo/tutorials.git ``` -------------------------------- ### Menu selection and GUI element markup combined Source: https://www.odoo.com/documentation/master/contributing/documentation/rst_guidelines.html Example showing combined use of :menuselection: and :guilabel: in a note. ```RST To configure the bill control policy, navigate to :menuselection:`Purchase --> Configuration --> Settings`, and scroll down to the :guilabel:`Invoicing` section. Under :guilabel:`Bill Control`, select either :guilabel:`Ordered quantities` or :guilabel:`Received quantities`. ``` -------------------------------- ### Upgrade script using Upgrade utils and ORM Source: https://www.odoo.com/documentation/master/developer/reference/upgrades/upgrade_scripts.html Example upgrade script that uses the Upgrade utils to access the ORM. It searches for all partners and appends an exclamation mark to each partner's name, then logs the total number of updated partners. ```python import logging from odoo.upgrade import util _logger = logging.getLogger(__name__) def migrate(cr, version): env = util.env(cr) partners = env["res.partner"].search([]) for partner in partners: partner.name += "!" _logger.info("Updated %s partners", len(partners)) ``` -------------------------------- ### Install rtlcss on Linux Source: https://www.odoo.com/documentation/master/administration/on_premise/source.html Install rtlcss globally using npm. Required for right-to-left interface languages. ```bash $ sudo npm install -g rtlcss ``` -------------------------------- ### Install web_enterprise module from source Source: https://www.odoo.com/documentation/master/administration/on_premise/community_to_enterprise.html Command to install the web_enterprise module when running Odoo from source code. ```bash $ -d -i web_enterprise --stop-after-init ```