### Clone Odoo Petstore Module Source: https://www.odoo.com/documentation/12.0/developer/howtos/web This command downloads the example Odoo module ('petstore') from GitHub. This module serves as a starting point for customizing the web client and testing the web framework. ```bash $ git clone http://github.com/odoo/petstore ``` -------------------------------- ### Start Odoo Server Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend Command to start the Odoo server. Ensure the full path to 'odoo-bin' is provided if it's not in your system's PATH. The server runs using a client/server architecture. ```bash odoo-bin ``` -------------------------------- ### Basic Counter Widget Example Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference An example demonstrating how to create a basic counter widget, including its template, initialization, event handling, and rendering. ```APIDOC ## Basic Counter Widget Example ### Description This example shows a simple counter widget with an increment button. It utilizes Odoo's event system and QWeb templating. ### Widget Definition ```javascript var Widget = require('web.Widget'); var Counter = Widget.extend({ template: 'some.template', events: { 'click button': '_onClick', }, init: function (parent, value) { this._super(parent); this.count = value; }, _onClick: function () { this.count++; this.$('.val').text(this.count); }, }); ``` ### Template (`some.template`) ```html
``` ### Usage ```javascript // Create the instance var counter = new Counter(this, 4); // Render and insert into DOM counter.appendTo(".some-div"); ``` ``` -------------------------------- ### Build and install pyflame Source: https://www.odoo.com/documentation/12.0/developer/howtos/profilecode This sequence of commands downloads the `pyflame` source code, configures the build environment, compiles the profiler, and installs it system-wide. It requires running `autogen.sh`, `configure`, and `make` before a final `sudo make install`. ```bash git clone https://github.com/uber/pyflame.git git clone https://github.com/brendangregg/FlameGraph.git cd pyflame ./autogen.sh ./configure make sudo make install ``` -------------------------------- ### Start Odoo Server with Custom Addons Path Source: https://www.odoo.com/documentation/12.0/developer/howtos/website This command starts the Odoo server, specifying additional directories where Odoo should look for modules. This is useful for loading newly developed or custom modules. ```bash $ ./odoo-bin --addons-path addons,my-modules ``` -------------------------------- ### Superlaser Endpoint Example Source: https://www.odoo.com/documentation/12.0/developer/webservices/iap An example of how the authorize, cancel, and capture functions might be used within a JSON-RPC endpoint. ```APIDOC ## Superlaser Endpoint Example ### Description An example of how the authorize, cancel, and capture functions might be used within a JSON-RPC endpoint. ### Method `POST` ### Endpoint `/deathstar/superlaser` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **user_account** (any) - Required - User account information. - **coordinates** (any) - Required - Target coordinates. - **target** (any) - Required - Target identifier. - **factor** (float) - Optional - Superlaser power factor (0.0 to 1.0). ### Request Example ```json { "jsonrpc": "2.0", "method": "call", "params": { "service": "deathstar.service", "method": "superlaser", "args": [ { "user_account": "some_account_token", "coordinates": {"x": 10, "y": 20}, "target": "Alderaan", "factor": 0.8 } ] } } ``` ### Response #### Success Response (200) - **result** (any) - The result of the superlaser operation. #### Response Example ```json { "jsonrpc": "2.0", "id": null, "result": "Superlaser fired successfully!" } ``` ### Error Handling - If an exception occurs during the process, the `cancel` function may be called, and the exception is re-raised. ``` -------------------------------- ### Odoo Account Template Example Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization An example of creating a specific account template record for 'Clients' in Odoo. It shows how to set the name, code, user type, and chart template ID. ```xml Clients 4000 ``` -------------------------------- ### Odoo TransactionCase Model Testing Example (Python) Source: https://www.odoo.com/documentation/12.0/developer/reference/testing Demonstrates how to test a model's properties and actions using `odoo.tests.common.TransactionCase`. Test methods must start with `test_`. This example creates a record, performs an action, and asserts the expected field value. ```python from odoo.tests import common class TestModelA(common.TransactionCase): def test_some_action(self): record = self.env['model.a'].create({'field': 'value'}) record.some_action() self.assertEqual( record.field, expected_field_value) # other tests... ``` -------------------------------- ### Widget Lifecycle Methods Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference Details on the various stages of a widget's lifecycle, including `init`, `willStart`, rendering, `start`, and `destroy`. ```APIDOC ## Widget Lifecycle ### Description The widget class follows a defined lifecycle: `init`, `willStart`, rendering, `start`, and `destroy`. ### `Widget.init(parent)` - **Description**: The constructor for the widget. Initializes the base state. - **Arguments**: - `parent` (`Widget()`): The parent widget, used for destruction and event propagation. Can be `null`. ### `Widget.willStart()` - **Description**: Called when a widget is created and about to be appended to the DOM. Should return a deferred. - **Purpose**: Useful for performing asynchronous operations before rendering. ### `[Rendering]` - **Description**: An automatic framework process. Renders the widget's template (if defined) or creates a DOM element based on `tagName`. Binds events defined in `events` and `custom_events`. - **Output**: Sets the widget's `$el` property. ### `Widget.start()` - **Description**: Called after rendering is complete. Useful for post-rendering tasks like library setup. - **Returns**: A deferred object indicating completion. ### `Widget.destroy()` - **Description**: The final step in a widget's life. Performs cleanup operations like unbinding events and removing the widget from the component tree. - **Note**: Automatically called when the parent is destroyed. Must be called explicitly if the widget has no parent or is removed independently. ``` -------------------------------- ### Example: VAT Leasing Tax Configuration in Odoo XML (l10n_pl) Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization This is a practical example of configuring a sales tax for vehicle leasing in Poland using Odoo's XML. It demonstrates how to set the tax name, description, amount, type, sequence, and link it to tax groups and tags. The `children_tax_ids` field shows how to group multiple tax components. ```xml VAT - leasing pojazdu(sale) VLP 1.00 group sale ``` -------------------------------- ### Install build dependencies for pyflame on Debian/Ubuntu Source: https://www.odoo.com/documentation/12.0/developer/howtos/profilecode These commands install the necessary development tools and libraries required to compile `pyflame` on Debian-based systems. This includes build utilities like `make`, `g++`, and development headers for Python. ```bash # These instructions are given for Debian/Ubuntu distributions sudo apt install autoconf automake autotools-dev g++ pkg-config python-dev python3-dev libtool make ``` -------------------------------- ### Python JSON-RPC Library for Odoo Interaction Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend A Python 3 program demonstrating how to interact with an Odoo server using the JSON-RPC protocol. It utilizes standard Python libraries `urllib.request` and `json`. The example shows logging into the database and creating a new note. It assumes the 'note' app is installed. ```python import json import random import urllib.request HOST = 'localhost' PORT = 8069 DB = 'openacademy' USER = 'admin' PASS = 'admin' def json_rpc(url, method, params): data = { "jsonrpc": "2.0", "method": method, "params": params, "id": random.randint(0, 1000000000), } req = urllib.request.Request(url=url, data=json.dumps(data).encode(), headers={ "Content-Type":"application/json", }) reply = json.loads(urllib.request.urlopen(req).read().decode('UTF-8')) if reply.get("error"): raise Exception(reply["error"]) return reply["result"] def call(url, service, method, *args): return json_rpc(url, "call", {"service": service, "method": method, "args": args}) # log in the given database url = "http://%s:%s/jsonrpc" % (HOST, PORT) uid = call(url, "common", "login", DB, USER, PASS) # create a new note args = { 'color': 8, 'memo': 'This is another note', 'create_uid': uid, } note_id = call(url, "object", "execute", DB, uid, PASS, 'note.note', 'create', args) ``` -------------------------------- ### Odoo XML: Belgian Chart of Accounts Example Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization This XML snippet provides a concrete example of defining a Belgian Chart of Accounts template. It sets the name, currency to EUR, bank and cash account prefixes, and specifies Dutch as the spoken language. ```xml Belgian PCMN 550 570 ``` -------------------------------- ### Client Action Example (ir.actions.client) Source: https://www.odoo.com/documentation/12.0/developer/reference/actions This snippet demonstrates how to trigger a client-side action using the 'ir.actions.client' type. It specifies the 'tag' to identify the client-side implementation, such as 'pos.ui' for the Point of Sale interface. Additional parameters can be passed via the 'params' dictionary. ```json { "type": "ir.actions.client", "tag": "pos.ui" } ``` -------------------------------- ### Compose Widgets Using appendTo() Source: https://www.odoo.com/documentation/12.0/developer/howtos/web This example demonstrates widget composition, where one widget (`HomePage`) includes another (`GreetingsWidget`). The `GreetingsWidget` is instantiated and then appended to a part of the `HomePage`'s root element (`$el`) using the `appendTo()` method. The `start()` method of the child widget is called during `appendTo()`. ```javascript local.HomePage = instance.Widget.extend({ start: function() { this.$el.append("
Hello dear Odoo user!
"); var greeting = new local.GreetingsWidget(this); return greeting.appendTo(this.$el); }, }); ``` -------------------------------- ### Python Dictionary Creation and Update Idioms Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines Shows preferred Python idioms for creating and updating dictionaries, favoring conciseness and readability over older methods. It includes examples for empty dictionaries, initializing with values, and updating existing dictionaries. ```python # -- 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) ``` -------------------------------- ### Odoo Module Initialization File Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend Example of an __init__.py file for an Odoo module. This file is essential for making the module a Python package and imports other Python files within the module. ```python from . import mymodule ``` -------------------------------- ### GET /academy// Source: https://www.odoo.com/documentation/12.0/developer/howtos/website A simple route that accepts a string parameter from the URL and displays it in an HTML heading. This demonstrates basic string extraction from the URL. ```APIDOC ## GET /academy// ### Description This endpoint accepts a string name from the URL and returns it within an H1 HTML tag. It serves as a basic example of URL parameter handling. ### Method GET ### Endpoint /academy// #### Path Parameters - **name** (string) - Required - The name to be displayed in the heading. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **HTML String** - A string containing an H1 tag with the provided name. #### Response Example ```html

Alice

``` ``` -------------------------------- ### Post-install Test Flag Source: https://www.odoo.com/documentation/12.0/developer/reference/testing Controls whether a test runs after module installations. Deprecated in favor of `tagged()`. ```APIDOC ## `odoo.tests.common.post_install` ### Description Sets the post-install state of a test. The flag is a boolean specifying whether the test should or should not run after a set of module installations. By default, tests are not run after installation of all modules in the current installation set. ### Method `post_install(flag)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from odoo.tests import common class TestMyModule(common.TransactionCase): @common.post_install(True) def test_post_install_feature(self): # Test logic here pass ``` ### Response #### Success Response (N/A) This is a decorator, not an endpoint. #### Response Example N/A ``` -------------------------------- ### Connecting to Odoo Demo Database Source: https://www.odoo.com/documentation/12.0/developer/webservices/odoo Examples in Python, Ruby, PHP, and Java to connect to the Odoo demo server and retrieve connection details. ```APIDOC ## Connecting to Odoo Demo Database ### Description This section provides examples for connecting to the Odoo demo server (`https://demo.odoo.com/start`) to obtain connection parameters such as host, database name, username, and password. ### Method XML-RPC calls to the `/start` endpoint. ### Endpoints - `https://demo.odoo.com/start` ### Parameters None directly for the `/start` endpoint, but the response contains: - **host** (string) - The server host address. - **database** (string) - The name of the demo database. - **user** (string) - The username for accessing the database. - **password** (string) - The password for authentication. ### Request Example ```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'] ``` ### Response Returns a dictionary containing connection details. ### Response Example ```json { "host": "some.host.com", "database": "demo_db_name", "user": "demo_user", "password": "demo_password" } ``` ``` -------------------------------- ### Odoo Javascript Module Definition Example Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference Demonstrates how to define Javascript modules in Odoo using the 'odoo.define' function. This includes basic module definition and module definition with explicit dependencies, showing how to import and use other modules. ```javascript odoo.define('module.A', function (require) { "use strict"; var A = ...; return A; }); odoo.define('module.B', function (require) { "use strict"; var A = require('module.A'); var B = ...; // something that involves A return B; }); ``` ```javascript odoo.define('module.Something', ['module.A', 'module.B'], function (require) { "use strict"; var A = require('module.A'); var B = require('module.B'); // some code }); ``` -------------------------------- ### RPC Call to Directly Access a Controller in JavaScript Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference This JavaScript example illustrates how to make an RPC call to directly access a controller on a specific route. It utilizes the `_rpc` helper, providing the route and any necessary parameters for the controller. ```javascript return this._rpc({ route: '/some/route/', params: { some: kwargs}, }); ``` -------------------------------- ### Running Odoo Tests from a Specific Module Source: https://www.odoo.com/documentation/12.0/developer/reference/testing This command-line example shows how to run tests exclusively from a particular Odoo module, such as 'sale', using the `odoo-bin` command with `--test-enable` and `--test-tags`. This is useful for isolating tests during development or debugging. ```bash odoo-bin --test-enable --test-tags sale ``` -------------------------------- ### Get Widget Children Source: https://www.odoo.com/documentation/12.0/developer/howtos/web Illustrates how to obtain a list of all direct child widgets of the current widget using the `getChildren()` method. The example accesses the root element of the first child widget in the returned array. ```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 }, }); ``` -------------------------------- ### Iterating Through a Recordset in Odoo Source: https://www.odoo.com/documentation/12.0/developer/reference/orm Illustrates how to iterate over an Odoo recordset. Each iteration yields a singleton recordset (containing a single record). This is analogous to iterating over a string to get individual characters. The example shows printing the recordset and individual records. ```python def do_operation(self): print self # => a.model(1, 2, 3, 4, 5) for record in self: print record # => a.model(1), then a.model(2), then a.model(3), ... ``` -------------------------------- ### Create Demo Course Products (XML) Source: https://www.odoo.com/documentation/12.0/developer/howtos/website XML records defining sample course products. Each record uses 'product.template' and links to the 'academy.category_courses' category. It sets the course as published on the website, defines a list price, and specifies the product type as 'service'. ```xml Course 0 True 0 service Course 1 True 0 service Course 2 True 0 service ``` -------------------------------- ### Get Start/End of Period in Odoo Source: https://www.odoo.com/documentation/12.0/developer/reference/orm These static methods, available on both `fields.Date` and `fields.Datetime`, allow you to easily calculate the start or end of a specified time period (year, quarter, month, week, day, hour) from a given date or datetime value. ```python # Get the start of the month for a given date start_of_month = fields.Date.start_of(some_date, 'month') # Get the end of the day for a given datetime end_of_day = fields.Datetime.end_of(some_datetime, 'day') ``` -------------------------------- ### Odoo SingleTransactionCase for Shared Test Transaction Source: https://www.odoo.com/documentation/12.0/developer/reference/testing Shows how to use `odoo.tests.common.SingleTransactionCase` where all test methods within a class execute within a single database transaction. The transaction starts with the first test and is rolled back only after the last test method completes. This is useful for tests that benefit from shared setup within a transaction. ```python import odoo.tests class TestSharedTransaction(odoo.tests.common.SingleTransactionCase): def test_first_method(self): # Logic that affects subsequent tests in the same transaction pass def test_second_method(self): # This method runs after test_first_method within the same transaction pass ``` -------------------------------- ### Running Odoo Tests with Specific Tags via Command Line Source: https://www.odoo.com/documentation/12.0/developer/reference/testing These command-line examples illustrate how to execute Odoo tests using the `odoo-bin` command with the `--test-enable` and `--test-tags` options. It shows how to run tests tagged with 'nice', combined tags like 'nice,standard', and how to exclude tests using a minus prefix like 'standard,-slow'. ```bash odoo-bin --test-enable --test-tags nice ``` ```bash odoo-bin --test-enable --test-tags nice,standard ``` ```bash odoo-bin --test-enable --test-tags 'standard,-slow' ``` -------------------------------- ### Odoo XML Naming Conventions for Views, Actions, Menus, and Security Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines Provides examples of naming conventions for various Odoo components including menus, views, actions, and security groups/rules. These conventions aid in maintaining consistency and organization within Odoo modules. No external dependencies are required. ```xml model.name.view.form ... model.name.view.kanban ... Model Main Action ... Model Access Children ... ... ... ``` -------------------------------- ### Odoo Inheritance Usage Example Source: https://www.odoo.com/documentation/12.0/developer/reference/orm Shows how to create and use models defined with classical inheritance in Odoo. This example demonstrates creating records of both the base and inherited models and calling their methods. ```python # Assuming Inheritance0 and Inheritance1 are defined as above a = env['inheritance.0'].create({'name': 'A'}) b = env['inheritance.1'].create({'name': 'B'}) result_a = a.call() result_b = b.call() # result_a will be "This is model 0 record A" # result_b will be "This is model 1 record B" ``` -------------------------------- ### Odoo Classical Inheritance Example Source: https://www.odoo.com/documentation/12.0/developer/reference/orm Demonstrates classical inheritance in Odoo, where a new model inherits fields and methods from a base model using _inherit. This example shows overriding a method. ```python class Inheritance0(models.Model): _name = 'inheritance.0' _description = 'Inheritance Zero' name = fields.Char() def call(self): return self.check("model 0") def check(self, s): return "This is {} record {}".format(s, self.name) class Inheritance1(models.Model): _name = 'inheritance.1' _inherit = 'inheritance.0' _description = 'Inheritance One' def call(self): return self.check("model 1") ``` -------------------------------- ### Python Function Return and Builtin Usage Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines Explains Python best practices for function returns and utilizing built-in functions for conciseness. It shows how to simplify multiple return points and effectively use `dict.get()` instead of redundant checks. ```python # Multiple return points are OK, when they’re simpler # a bit complex and with a redundant temp variable # def axes(self, axis): # axes = [] # if type(axis) == type([]): # axes.extend(axis) # else: # axes.append(axis) # return axes # clearer def axes(self, axis): if type(axis) == type([]): return list(axis) # clone the axis else: return [axis] # single-element list # Know your builtins # value = my_dict.get('key', None) # very very redundant value = my_dict.get('key') # good ``` -------------------------------- ### Running Odoo Tests from a Module or with a Specific Tag Source: https://www.odoo.com/documentation/12.0/developer/reference/testing This command-line example shows how to run tests from either the 'stock' module or any test tagged as 'slow'. It uses the `odoo-bin` command with `--test-enable` and `--test-tags`, illustrating additive tag selection. ```bash odoo-bin --test-enable --test-tags '-standard, slow, stock' ``` -------------------------------- ### Timesheet Pivot View Example Source: https://www.odoo.com/documentation/12.0/developer/reference/views A comprehensive example of an Odoo pivot view for timesheet data. It includes grouping by employee and date (monthly interval), and aggregating unit amount with a float time widget. ```xml ``` -------------------------------- ### Create a Basic Odoo Controller Source: https://www.odoo.com/documentation/12.0/developer/howtos/website This Python code defines a simple Odoo controller that handles web requests. It imports the necessary Odoo components and defines a route that returns a 'Hello, world' string. ```python # -*- coding: utf-8 -*- from odoo import http class Academy(http.Controller): @http.route('/academy/academy/', auth='public') def index(self, **kw): return "Hello, world" ``` -------------------------------- ### Odoo Filter Example Source: https://www.odoo.com/documentation/12.0/developer/reference/views An example of an Odoo filter definition within an XML view. The 'name' attribute is a logical identifier, 'string' provides a display label, and 'context' specifies grouping behavior, here by the week of the creation date. ```xml ``` -------------------------------- ### Python Iteration and Dictionary `setdefault` Usage Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines Advises on efficient Python iteration techniques, favoring direct dictionary iteration over `.keys()` and showing the utility of `dict.setdefault()` for simplifying the creation of default dictionary values. ```python # Iterate on iterables # creates a temporary list and looks bar # for key in my_dict.keys(): # "do something..." # better for key in my_dict: "do something..." # accessing the key,value pair for key, value in my_dict.items(): "do something..." # Use dict.setdefault # longer.. harder to read # values = {} # for element in iterable: # if element not in values: # values[element] = [] # values[element].append(other_value) # Use setdefault for cleaner code values = {} for element in iterable: values.setdefault(element, []).append(other_value) ``` -------------------------------- ### Override Chart of Accounts Properties Example (XML) Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization This is an example in XML showing how to override specific properties for a Chart of Accounts, such as the Belgian PCMN. It sets particular accounts for receivables, payables, expenses, income, currency exchange, and transfers. ```xml ``` -------------------------------- ### Alternative Odoo Page Creation with QWeb Template (XML) Source: https://www.odoo.com/documentation/12.0/developer/howtos/themes Demonstrates an alternative method for creating Odoo website pages by defining a QWeb template directly. This approach embeds the page content, including a snippet area, within the `