Odoo 12 Development Cookbook - Third Edition

4.6 (8 reviews total)
By Alexandre Fayolle , Parth Gajjar , Holger Brunn and 1 more
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Installing the Odoo Development Environment

About this book

Odoo is a powerful framework known for rapid application development. Its latest release, Odoo 12, introduces tons of new features. With this book, you’ll learn how to develop powerful Odoo applications from scratch, using all the latest features.

This Odoo cookbook starts by covering Odoo installation and deployment on the server. Next, you’ll explore the Odoo framework with real-world examples. You’ll create a new Odoo module from the ground up and progress to advanced framework concepts. You’ll also learn how to modify existing applications, including Point of Sale (POS). This book is not just limited to backend development; the advanced JavaScript recipes for creating new views and widgets will help you build beautiful UI elements. As you move forward, you’ll gain insights into website development and become a quality Odoo developer by studying performance optimization, debugging, and automated tests. Finally, you’ll learn the latest concepts like multi-website, In-App Purchasing (IAP), Odoo.sh, and IoT Box.

By the end of the book, you’ll have all the knowledge you need to build powerful Odoo applications. The development best practices used in this book will undoubtedly come handy when you are working with the Odoo framework.

Publication date:
April 2019
Publisher
Packt
Pages
774
ISBN
9781789618921

 

Chapter 1. Installing the Odoo Development Environment

In this chapter, we will cover the following recipes:

  • Odoo ecosystem
  • Easy installation of Odoo from source
  • Managing Odoo environments using the start command
  • Managing Odoo server databases
  • Storing the configuration instance in a file
  • Activating Odoo developer tools
  • Updating Odoo from source
 

Introduction


There are lots of ways to set up an Odoo development environment. This chapter proposes one of them; you will certainly find a number of other tutorials on the web explaining other approaches. Keep in mind that this chapter is about a development environment that has different requirements from a production environment. This will be covered in Chapter 3, Server Deployment.

If you are new to Odoo development, you must know about certain aspects of the Odoo ecosystem. The next section will give you a brief introduction to those aspects, and then we will move on to the installation of Odoo for development.

 

 

Odoo ecosystem


Odoo provides the developer with out-of-the-box modularity. Its powerful framework helps the developer to build projects very quickly. There are various characters in the Odoo ecosystem that you should be familiar with before starting your journey of becoming a successful Odoo developer.

Odoo editions

Odoo comes with two editions. The first is the Community Edition, which is open source, and the second is the Enterprise Edition, which has licensing fees. Unlike other software vendors, Odoo Enterprise Edition is just a bunch of advance applications that adds extra features/apps in the Community Edition. Basically, Enterprise Edition runs on top of the Community Edition. The Community Edition comes under the Lesser General Public License v3.0 (LGPLv3) license and comes with all of the basic Enterprise resource planning(ERP) applications, such as sale, Customer Relationship Management (CRM), invoicing, purchase, website builder, and so on. Alternatively, Enterprise Edition comes with the Odoo Enterprise Edition License, which is a proprietary license. Odoo Enterprise Edition comes with advanced features such as full accounting, studio, Voice over Internet Protocol (VoIP), mobile responsive design, e-sign, marketing automation, and delivery and banking integrations. Enterprise Edition also provides you with unlimitedbugfixes. The following diagram shows that Enterprise Edition depends on the Community Edition, which is why you need Community Edition to use Enterprise Edition:

You can see a full comparison of both editions here: https://www.odoo.com/page/editions.

 

Note

Odoo has the largest number of community developers, which is why you will find a large number of third-party apps (modules) on the app store. Most of the free apps use an Affero General Public License version 3 (AGPLv3). You cannot use the proprietary license on your app if your application has dependencies on such apps. Apps with an Odoo proprietary license can be developed only on modules that have LGPL or other proprietary licenses.

Git repositories

The whole code base of Odoo is hosted on GitHub. You can post bugs/issues for stable versions here. You can also propose a new feature by submitting Pull Requests (PR). There are several repositories in Odoo; see the following table for more information:

Repositories

Purpose

https://github.com/odoo/odoo

This is the Community Edition of Odoo. It's available publicly.

https://github.com/odoo/enterprise

This is the Enterprise Edition of Odoo. It's available to official Odoo partners only.

https://github.com/odoo-dev/odoo

This is an Ongoing development repository. It's available publicly.

 

Every year, Odoo releases one major (Long Term Support (LTS)) version and a few minor versions. Minor versions are mostly used in Odoo's online SaaS service, meaning that Odoo SaaS users get early access to these features. Major version branches have names such as 12.0, 11.0, and 10.0, while minor version branches have names such as saas-12.1, saas-11.1, and saas-11.2 on GitHub. The master branch is under development and is subject to change at any time. Consequently, it is advisable not to use this for production, since it might break down your database.

Runbot

Runbot is Odoo's automated testing environment. This pulls the latest branches from Odoo's Git repositories and creates the builds for the last four commits. Here, you can test all stable and in-development branches. You can even play with the Enterprise Edition and its development branches.

 

Every build has a different background color, which indicates the status of the test cases. A green background color means that all of the test cases run successfully and you can test that branch, while a red background color means that some test cases have failed on this branch and some features might be broken on that build. You can view the logs for all test cases, which show exactlywhat happens during installation. Every build has two databases. Theall database has all of the modules installed on it, while thebasedatabase only has base Odoo modules installed. Every build is installed with basic demo data, and therefore you can test it quickly without extra configurations.

Note

You can access runbot with from the following URL: http://runbot.odoo.com/runbot.

The following credentials can be used to access any runbot build:

  • Login ID: admin Password: admin
  • Login ID:demo Password: demo
  • Login ID:portalPassword: portal

Note

This is a public testing environment, so sometimes it is possible that other users are using/testing the same branch that you are testing.

Odoo app store

Odoo launched the app store a few years back, and this was an instant success. Right now, there are over 15,000 different apps hosted there. In the app store, you will find lots of free and paid applications for different versions. This includes specific solutions for different business verticals, such as education, food industries, and medicine. It also includes apps that extend/add new features to existing Odoo applications. The app store also provides numerous beautiful themes for the Odoo website builder. In Chapter 4, Creating Odoo Add-On Modules, we will look at how you can set pricing and currency for your custom module.

You can access the Odoo app store via the following URL: https://www.odoo.com/apps.

 

Odoo community association

Odoo Community Association (OCA) is a non-profit organization that develops/manages community-based Odoo modules. All OCA modulesare open source and maintained by Odoo community members. Under the OCA's GitHub account,you will find multiple repositories for different Odoo applications. Apart from Odoo modules, it also contains various tools, a migration library, accounting localizations, and so on.

Here is the URL for OCA's official GitHub account: https://github.com/OCA.

Official Odoo help forum

Odoo has a very powerful framework, and tons of things can be achieved just by using/activating options or by following specific patterns. Consequently, if you run into some technical issues or if you are not sure about some complex cases, then you can post your query on Odoo's official help forum. Lots of developers are active on this forum, including some official Odoo employees.

You can search for or post your questions at the following URL: https://help.odoo.com.

 

Easy installation of Odoo from a source


For Odoo deployment, it is recommended to use a GNU/Linux environment. You may be more at ease using Microsoft Windows or Mac OS X, but the fact is that most Odoo developers use GNU/Linux, and you are much more likely to get support from the community for OS-level issues that occur on GNU/Linux than on Windows.

It is also recommended to develop using the same environment (the same distribution and the same version) as the one that will be used in production. This will avoid nasty surprises, such as discovering on the day of deployment that a library has a different version than expected with slightly different and incompatible behavior. If your workstation is using a different OS, a good approach is to set up a Virtual Machine (VM) on your workstation and install a GNU/Linux distribution in the VM.

 

Note

To avoid copying files between the workstation where you are running your development environment and the VM that runs Odoo, you can configure a SAMBA share inside the VM and store the source code there. You can then mount the share on your workstation in order to edit the files easily.

This book assumes that you are running Debian GNU/Linux as its stable version (this is version 9, code name Stretch, at the time of writing). Ubuntu is another popular choice, and since it is built on top of Debian, most of the examples in this book should work without needing to be changed. Whatever Linux distribution you choose, you should have some notion of how to use it from the command line, and having knowledge about system administration will certainly not cause any harm.

Getting ready

We are assuming that you have Linux up and running and that you have an account with root access, either because you know the root password, or because sudo has been configured. In the following sections, we will use $(whoami) whenever the login of your work user is required in a command line. This is a shell command that will substitute your login in the command you are typing.

Some operations will definitely be easier if you have a GitHub account. If you don't have one already, go to https://github.com and create one.

How to do it...

To install Odoo from a source, you need to follow these steps:

  1. Run the following commands to install the main dependencies:
$ sudo apt-get update
$ sudo apt-get install -y git python3.5 postgresql nano virtualenv xz-utils wget fontconfig libfreetype6 libx11-6 libxext6 libxrender1 xfonts-75dpi

Note

Odoo v12 has moved from less to scss for stylesheet preprocessing. Consequently, if you are using <v12, then you need to install node-less node-clean-css in order to get the correct stylesheets.

  1. Download and install wkhtmltopdf:
$ wget -O wkhtmltox.tar.xz \ https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz 
$ tar xvf wkhtmltox.tar.xz
$ sudo mv wkhtmltox/lib/* /usr/local/lib/
$ sudo mv wkhtmltox/bin/* /usr/local/bin/
$ sudo mv wkhtmltox/share/man/man1 /usr/local/share/man/
  1. Now, use the following code to install the build dependencies:
$ sudo apt-get install -y gcc python3.5-dev libxml2-dev \
libxslt1-dev libevent-dev libsasl2-dev libssl1.0-dev libldap2-dev \
libpq-dev libpng-dev libjpeg-dev
  1. Configure PostgreSQL:
$ sudo -u postgres createuser --createdb $(whoami)
$ createdb $(whoami)
  1. Configure git:
$ git config --global user.name "Your Name"
$ git config --global user.email [email protected]
  1. Clone the Odoo code base:
$ mkdir ~/odoo-dev
$ cd ~/odoo-dev
$ git clone -b 12.0 --single-branch\ https://github.com/odoo/odoo.git
$ cd odoo
  1. Create an odoo-12.0 virtual environment and activate it:
$ virtualenv -p python3 ~/odoo-12.0
$ source ~/odoo-12.0/bin/activate
  1. Install the Python dependencies of Odoo in virtualenv:
$ pip3 install -r requirements.txt
  1. Create and start your first Odoo instances:
$ createdb odoo-test
$ python3 odoo-bin -d odoo-test --addons-path=addons \ 
--db-filter=odoo-test$

 

  1. Point your browser to http://localhost:8069and authenticate it by using theadminaccount and usingadminas the password.

Note

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed to you directly.

You can download the code files by following these steps:

  1. Log in or register on our website using your email address and password
  2. Hover the mouse pointer over the SUPPORT tab at the top
  3. Click on Code Downloads and Errata
  4. Enter the title of this book in the search box
  5. Select the book that you're looking to download the code files for
  6. Choose where you purchased this book from in the drop-down menu
  7. Click on Code Download

You can also download the code files by clicking on the Code Files button on this book's web page on the Packt Publishing website. This page can be accessed by entering this book's title in the search box. Note that you need to be logged into your Packt account to do this.

Once the file has been downloaded, ensure that you unzip or extract the folder using the latest version of the following tool:

  • WinRAR/7-Zip for Windows

  • Zipeg/iZip / UnRarX for Mac

  • 7-Zip/PeaZip for Linux

 

How it works...

Dependenciescome from various sources. First, you have the core dependencies of Odoo, the Python interpreter, which is used to run the source code, and the PostgreSQL database server, which is used to store the instance data. Git is used for source code versioning and getting the source code of Odoo itself.

Note

Prior to 11.0, versions of Odoo ran with Python 2.7. Starting with Odoo 11.0, the minimum supported version of Python is 3.5. These two versions of Python are not compatible, so a module running on Python 2.7 (with Odoo 9.0 or 10.0, for instance) will require both porting to the specifics of Odoo 11.0 and porting to Python 3.

Since we will need to edit some files as rootor aspostgres(the PostgreSQL administrative user) on our server, we need to install a console-based text editor. We suggestnano for this as it is very simple to use, but feel free to choose any editor that you feel at ease with, as long as it works on the Console. For example, you can use vim,e3, oremacs-nox.

Wkhtmltopdfis a runtime dependency of Odoo that's used to produce PDF reports. The version that's required by Odoo 12.0 is 0.12.4, which is not included in the current GNU/Linux distributions. Fortunately for us, the maintainers of wkhtmltopdf provide pre-built packages for various distributions athttp://wkhtmltopdf.org/downloads.html.

There are lots of other runtime dependencies that are Python modules, which we can install using pip3in a virtual environment. However, some of these Python modules can feature some dependencies on native C libraries, for which the Python bindings need to be compiled. Consequently, we install the development packages for these C libraries as well as the Python development package and a C compiler. Once these build dependencies are installed, we can usepip3 install -r requirements.txt(a file that comes from the Odoo source code distribution) to download, compile, and install the Python modules.

Virtual environments

Python virtual environments, or virtualenvfor short, are isolated Python workspaces. These are very useful to Python developers because they allow different workspaces with different versions of various Python libraries to be installed, possibly on different Python interpreter versions.

 

 

You can create as many environments as you wish using the virtualenv -p python3 path/to/newenvcommand. This will create anewenvdirectory in the specified location, containing abin/ subdirectory and a lib/python3.5subdirectory. Don't forget -p python3, or you are likely to get a Python 2.7 virtual environment that won't be able to run Odoo 12.0.

In bin/, you will find several scripts:

  • activate: This script is not executed and is sourced using the shell's built-insourcecommand. This will activate the environment by adjusting thePATHenvironment variable to include thebin/directoryofvirtualenv. It also installs a shell function calleddeactivate, which you can run in order to exitvirtualenv, and changes the shell prompt to let you know whichvirtualenvis currently activated.
  • pip3: This is a special version of thepip3command that acts insidevirtualenvonly.
  • python3: This is a wrapper around your system's Python interpreter, which uses the packages that have been installed invirtualenv.

Note

The shell built-in source command is also available as . (a single dot, followed by a space and the path to the file to source.) This means you can use .~/odoo-12.0/bin/activate instead of source~/odoo-12.0/bin/activate.The shortcut form is perfectly fine, but we will stick to the source in this book for the purpose of readability.

There are two main ways of using avirtualenv. You may activate it, as shown in this recipe (and calldeactivatewhen you're done), or you may use the scripts in thebin/directory of the environment explicitly by calling them with their full path, in which case you don't need to activate thevirtualenvscript. This is mainly a matter of taste, so you should experiment and find out which style suits you better.

You may have executable Python scripts within the first line. This should look as follows:

#! /usr/bin/env python3

These will be easier to use with an activated virtualenvscript.

 

This is the case with the odoo-binscript, which you can call in the following way:

$ ./odoo-bin -d odoo-test --addons-path=addons --db-filter=odoo-test

PostgreSQL configuration

On a GNU/Linux system, Odoo uses the psycopg2 Python library to connect with a PostgreSQL database. Odoo works very well with the default values, which are used to access a PostgreSQL database with psycopg2. It uses the following default values:

  • By default, psycopg2 tries to connect to a database with the same username as the current user on local connections, which enables password-less authentication
  • The local connection uses Unix domain sockets
  • The database server listens on port 5432

There is nothing special to do here, so we simply use the postgresadministrative user to create a database user who shares our login name and gives it the right to create new databases. We then create a new database with the same name as the new user. Thiswill be used as a default database when we use thepsqlcommand.

When on a development server, it is okay to give the PostgreSQL user more rights and use the --superusercommand-line option rather than just--createdb. The net effect is that this user can then also create other users and globally manage the database instance. If you feel that--superuseris too much, you may still want to use--createrolein addition to--createdbwhen creating your database user. Avoid doing this on production servers as it will give additional leverage to an attacker exploiting a vulnerability in some part of the deployed code (refer toChapter 3, Server Deployment).

If you want to use a database user with a different login, you will need to provide a password for the user. This is done by passing the --pwpromptflag on the command line when creating the user, in which case the command will prompt you for the password.

If the user has already been created and you want to set a password (or modify a forgotten password), you can use the following command:

$ psql -c "alter role $(whoami) with password 'newpassword'"

Note

If this command fails with an error message saying that the database does not exist, it is because you did not create a database named after your login name in step 4 of this recipe. That's fine; just add the --dbname option with an existing database name, such as --dbname template1.

Git configuration

At some point in this book, you will need to use git commit. This will fail unless some basic configuration is performed; therefore, you need to provide Git with your name and email address. Git will remind you to do this with a nice error message, but you may as well do it now.

Note

This is also something to keep in mind if you are using a service such as Travis for continuous integration, and your test scripts need to perform some git merges. You have to provide a dummy name and email for the merging to succeed.

Downloading the Odoo source code

Downloading the Odoo code base is done by performing a git cloneoperation; be patient, as this will take some time. The--branch 12.0 --single-branch options avoid downloading other branches and save a little time. The--depthoption can also be used to avoid downloading the whole repository history, but the downside of that option is that you will not be able to explore that history when looking for issues.

Odoo developers also propose nightly builds, which are available as tarballs and distribution packages. The main advantage of using git clone is that you will be able to update your repository when new bug fixes are committed in the source tree. You will also be able to easily test any proposed fixes and track regressions so that you can make your bug reports more precise and helpful for developers.

Starting the instance

Now comes the moment you've been waiting for. To start our first instance, we first create a new empty database and then use the odoo-binscript with the following command-line arguments:

  • -d database_name: Use this database by default.
  • --db-filter=database_name$: Only try to connect to databases that match the supplied regular expression. One Odoo installation can serve multiple instances that live in separate databases, and this argument limits the available databases. The trailing$is important as the regular expression is used in match mode; this allows to to avoid selecting names starting with the specified string.
  • --addons-path=directory1,directory2,...: This is a comma-separated list of directories in which Odoo will look for add-ons. This list is scanned at instance creation time to populate the list of available add-on modules in the instance.

If you are using a database user with a database login that is different from your Linux login, you need to pass the following additional arguments:

  • --db_host=localhost: Use a TCP connection to the database server
  • --db_user=database_username: Use the specified database login
  • --db_password=database_password: This is the password for authenticating against the PostgreSQL server

To get an overview of all available options, use the --helpargument. We will see more of theodoo-binscript later in this chapter, as well as inChapter 2, Managing Odoo Server Instances.

When Odoo is started on an empty database, it will first create the database structure that's needed to support its operations. It will also scan the add-ons path to find the available add-on modules and insert some into the initial records in the database. This includes the adminuser with the defaultadminpassword,which you will use for authentication.

Odoo includes an HTTP server. By default, it listens on all local network interfaces on TCP port 8069, so pointing your web browser tohttp://localhost:8069/leads you to your newly created instance.

 

 

Managing Odoo environments using the start command


We will often want to use custom or community modules with our Odoo instance. Keeping them in a separate directory makes it easier to install upgrades to Odoo or troubleshoot issues from our custom modules. We just have to add that directory to the add-ons path and they will be available in our instance, just like the core modules are.

It is possible to think about this module directory as an Odoo environment. The Odoo startcommand makes it easy to organize Odoo instances as directories, each with its own modules.

Getting ready

For this recipe, we need to have already installed Odoo. We are assuming that it will be located at ~/odoo-dev/odoo, and thatvirtualenvhas been activated.

This means that the following command should successfully start an Odoo server:

$ ~/odoo-dev/odoo/odoo-bin

How to do it...

To create a work environment for your instance, you need to follow these steps:

  1. Change to the directory where Odoo is:
$ cd ~/odoo-dev
  1. Choose a name for the environment and create a directory for it:
$ mkdir my-odoo
  1. Change to that directory and start an Odoo server instance for that environment:
$ cd my-odoo/
$ ../odoo/odoo-bin start

 

How it works...

The Odoo startcommand is a shortcut to start a server instance using the current directory. The directory name is automatically used as the database name (for the-doption), and the current directory is automatically added to the add-ons path (the --addons-pathoption), as long as it contains an Odoo add-on module. In the preceding recipe, you won't see the current directory in the add-ons path because it doesn't contain any modules yet.

Note

With the start command, if you are on the virtual environment, it will take the virtual environment name as the database instead of the directory that you are in. However, if you aren't in the virtual environment, this should work fine.

There's more…

By default, the current directory is used, but the --pathoption allows you to set a specific path that you can use instead. For example, this will work from any directory:

$ ~/odoo-dev/odoo/odoo-bin start --path=~/odoo-dev/my-odoo

The database to use can also be overridden using the usual -doption. In fact, all of the other usualodoo-bincommand-line argumentswill work, except--addons-path. For example,to set the server listening port, use the following command:

$ ../odoo/odoo-bin start -p 8080 -i base

As we can see, the Odoo startcommand can be a convenient way to quick-start Odoo instances with their own module directory.

 

Managing Odoo server databases


When working with Odoo, all of the data of your instance is stored in a PostgreSQL database. All of the standard database management tools you are used to are available, but Odoo also proposes a web interface for some common operations.

Getting ready

We are assuming that your work environment is set up and that you have an instance running. Do not start this using the odoo-bin startcommand that was shown in the previous recipe, as this configures the server with some options that interfere with multi-database management.

How to do it...

The Odoo database management interface provides tools to create, duplicate, remove, back up, and restore a database. There is also a way to change the master password, which is used to protect access to the database management interface.

Accessing the database management interface

To access the database, the following steps need to be performed:

  1. Go to the login screen of your instance (if you are authenticated, log out).
  2. Click on the Manage Databaseslink. This will navigate tohttp://localhost:8069/web/database/manager(you can also point your browser directly to that URL).

Setting or changing the master password

If you've set up your instance with default values and haven't modified it yet, as we will explain in the following section, the database management screen will display a warning, telling you that the master password hasn't been set and will advise you to set one with a direct link:

To set the master password, you need to perform the following steps:

  1. Click on the Set Master Password button. You will get a dialog box asking you to provide the New Master Password:
  1. Type in a non-trivial new password and click on Continue

If the master password is already set, click on theSetMaster Password button at the bottom of the screen to change it. In the displayed dialog box, type the previous masterpassword and the new one and then click onContinue.

Note

The master password is the server configuration file under the admin_password key. If the server was started without specifying a configuration file, a new one will be generated in ~/.odoorc. See the next recipe for more information about the configuration file.

Creating a new database

This dialog box can be used to create a new database instance that will be handled by the current Odoo server:

  1. In the database management window, click on theCreate Databasebutton, which can be found at the bottom of the screen:
  1. Fill in the form, as follows:
    • Master Password: This is the master password for this instance.
    • Database Name: Input the name of the database you wish to create.
    • Password:Type in the password you want to set for the admin user of the new instance.
    • Phone Number: Set the phone number (optional).
    • Language: Select the language you wish to be installed by default in the new database in the drop-down list.
    • Country: Select the country of the main company in the drop-down list. Selecting this will automatically configure a few things, such as company currency.
    • Load demonstration data: Check this box to obtain demonstration data. This is useful for running interactive tests or setting up a demonstration for a customer, but it should not be checked for a database that is designed to contain production data.

Note

If you wish to use the database to run the automated tests of the modules (refer to Chapter 8, Debugging and Automated Testing), you need to have the demonstration data, as the vast majority of the automated tests in Odoo depend on these records in order to run successfully.

  1. Click on theContinuebutton and wait a while until the new database is initialized. You will then be redirected to the instance and connected as the administrator.

Note

Troubleshooting:If you are redirected to a login screen, this is probably because the --db-filter option was passed to Odoo and the new database name didn't match the new database name. Note that the odoo-bin start command does this silently, making only the current database available. To work around this, simply restart Odoo without the start command, as shown in the Easy installation of Odoo from a source recipe of this chapter. If you have a configuration file (refer to the Storing the instance configuration in a file recipe later in this chapter), then check that the db_filter option is unset or set to a value matching the new database name.

 

Duplicating a database

Often, you will have an existing database, and you will want to experiment with it to try a procedure or run a test, but without modifying the existing data. The solution here is simple: duplicate the database and run the test on the copy. Repeat this as many times as required:

  1. In the database management screen, click on theDuplicate Databaselink next to the name of the database you wish to clone:
  1. Fill in the form as follows:
    • Master Password: This is the master password of the Odoo server
    • New Name: The name you want to give to the copy
  1. Click on theContinuebutton.
  2. You can then click on the name of the newly created database in the database management screen to access the login screen for that database.

Removing a database

When you have finished your tests, you will want to clean up the duplicated databases. To do this, perform the following steps:

  1. In the database management screen, click on theDelete Databaselink next to the name of the database you want to remove:
  1. Fill in the form and enter theMaster Password, which is the master password of the Odoo server.
  2. Click on theDeletebutton.

Note

Caution! Potential data loss!

If you selected the wrong database, and have no backup, there is no way to recover the lost data.

Backing up a database

For creating a backup, the following steps need to be performed:

  1. In the database management screen, click on the Backup Database link next to the database you want to back up:
  1. Fill in the form:
    • Master Password: This is the master password of the Odoo server.
    • Backup Format: Always usezipfor a production database, as it is the only real full backup format. Only use thepg_dumpformat for a development database when you don't really care about the file store.
  1. Click on the Backup button. The backup file will then be downloaded to your browser.

Restoring a database backup

If you need to restore a backup, this is what you need to do:

  1. In the database management screen, click on the Restore Database button at the bottom of the screen:
  1. Fill in the form:
    • Master Password: This is the master password of the Odoo server.
    • File: This is a previously downloaded Odoo backup.
    • Database Name: Provide the name of the database in which the backup will be restored. The database must not exist on the server.
    • This database might have been moved or copied: Choose This database wasmoved if the original database was on another server or if it has been deleted from the current server. Otherwise, choose This database is a copy, which is the safe default option.
  2. Click on theContinuebutton.

Note

It isn't possible to restore a database on top of itself. If you try to do this, you will get an error message (Database restore error: Database already exists). You need to remove the database first.

How it works...

These features, apart from theChange master passwordscreen, run PostgreSQLadministration commands on the server and report back through the web interface.

The master password is a very important piece of information that only lives in the Odoo server configuration file and is never stored in the database. There used to be a default value ofadmin, but using this value is a security liability, which is well-known. In Odoo v9 and later, this is identified as an unset master password, and you are urged to change it when accessing the database administration interface. Even if it is stored in the configuration file under theadmin_passwdentry, this isnotthe same as the password of theadminuser; these are two independent passwords. The master password is set for an Odoo server process, which itself can handle multiple database instances, each of which has an independentadminuser with their own password.

 

Note

Security considerations: Remember that we are considering a development environment in this chapter. The Odoo database management interface is something that needs to be secured when you are working on a production server, as it gives access to a lot of sensitive information, especially if the server hosts Odoo instances for several different clients. This will be covered inChapter 3, Server Deployment.

To create a new database, Odoo uses the PostgreSQLcreatedbutility and calls the internal Odoo function to initialize the new database in the same way as when you start Odoo on an empty database.

To duplicate a database, Odoo uses the--templateoption ofcreatedb, passing the original database as an argument. This essentially duplicates the structure of the template database in the new database using internal and optimized PostgreSQL routines, which is much faster than creating a backup and restoring it (especially when using the web interface, which requires downloading the backup file and uploading it again).

Backup and restore operations use thepg_dumpandpg_restoreutilities, respectively. When using thezipformat, the backup will also include a copy of the file store that contains a copy of the documents when you configure Odoo to not keep these in the database, which is the default option in 12.0. Unless you change it, these files live in~/.local/share/Odoo/filestore.

Note

If the backup gets large, downloading it may fail. This is either because the Odoo server itself is unable to handle the large file in memory or because the server is running behind a reverse proxy (refer toChapter 3, Server Deployment) because there is a limit to the size of HTTP responses that were set in the proxy. Conversely, for the same reasons, you will likely experience issues with the database restore operation. When you start running into these issues, it is time to invest in a more robust external backup solution.

There's more...

Experienced Odoo developers generally don't use the database management interface and perform operations from the command line. To initialize a new database with demo data, for instance, the following one-liner can be used:

$ createdb testdb && odoo-bin -d testdb

 

 

 

 

The additional bonus of this command line is that you can request the installation of add-ons while you are using, for instance,-i sale,purchase,stock(more on this inChapter 2, Managing Odoo Server Instances).

To duplicate a database, stop the server and run the following commands:

$ createdb -T dbname newdbname
$ cd ~/.local/share/Odoo/filestore # adapt if you have changed the data_dir
$ cp -r dbname newdbname
$ cd -

Note that, in the context of development, the file store is often omitted.

Note

The use of createdb -T only works if there are no active sessions on the database, which means that you have to shut down your Odoo server before duplicating the database from the command line.

To remove an instance, run the following command:

$ dropdb dbname
$ rm -rf ~/.local/share/Odoo/filestore/dbname

To create a backup (assuming that the PostgreSQL server is running locally), use the following command:

$ pg_dump -Fc -f dbname.dump dbname
$ tar cjf dbname.tgz dbname.dump ~/.local/share/Odoo/filestore/dbname

To restore the backup, run the following command:

$ tar xf dbname.tgz
$ pg_restore -C -d dbname dbname.dump

Note

Caution!

If your Odoo instance uses a different user to connect to the database, you need to pass -U username so that the correct user is the owner of the restored database.

 

 

Storing the instance configuration in a file


Theodoo-binscript has dozens of options, and it is tedious to remember them, all as well as remembering to set them properly when starting the server. Fortunately, it is possible to store them all in a configuration file and to only specify by hand the ones you want to alter, for example, for development.

How to do it...

To generate a configuration file for your Odoo instance, run the following command:

$ ./odoo-bin --save --config myodoo.cfg --stop-after-init

You can add additional options, and their values will be saved in the generated file. All of the unset options will be saved with their default value set. To get a list of possible options, use the following command:

$ ./odoo-bin --help | less

This will provide you with some help about what the various options perform. To convert from the command-line form into the configuration form, use the long option name, remove the leading dashes, and convert the dashes in the middle into underscores:--without-demo then becomeswithout_demo. This works for most options, but there are a few exceptions, which are listed in the following section.

Edit themyodoo.cfg file (use the table in the following section for some parameters you may want to change). Then, to start the server with the saved options, run the following command:

$ ./odoo-bin -c myodoo.cfg

Note

The --config option is commonly abbreviated as -c.

 

 

 

How it works...

At startup, Odoo loads its configuration in three passes. First, a set of default values for all options is initialized from the source code, then the configuration is parsed, and any value that's defined in the file overrides the defaults. Finally, the command-line options are analyzed and their values override the configuration that was obtained from the previous pass.

As we mentioned earlier, the names of the configuration variables can be found from the names of the command-line options by removing the leading dashes and converting the middle dashes into underscores. There are a few exceptions to this, notably the following:

Command line

Configuration file

--db-filter

dbfilter

--no-http

http_enable = True/False

--database

db_name

--dev

dev_mode

--i18n-import/--i18n-export

Unavailable

 

Here's a list of options that are commonly set through the configuration file:

Option

Format

Usage

without_demo

Comma-separated list of module names, or all (to disable demo data for all modules), or False (to enable demo data for all modules)

This prevents module demo data from being loaded.

addons_path

Comma-separated list of paths

This is a list of directory names in which the server will look for add-ons (refer toChapter 2, Managing Odoo Server Instances).

admin_passwd

Text

This is the master password (take a look at the preceding recipe).

data_dir

Path to a directory

This is a directory in which the server will store session information, add-ons downloaded from the internet, and documents if you enable the file store.

db_host

Hostname

This is the name of the server running the PostgreSQL server. Use Falseto use local Unix Domain sockets, andlocalhostto use TCP sockets locally.

db_user

Database user login

This is generally empty ifdb_hostisFalse. This will be the name of the user used for connecting database.

db_password

Database user password

This is generally empty if db_hostisFalseand when db_userhas the same name as the user running the server. Read the main page ofpg_hba.conffor more information on this.

db_name

Database name

This is used to set the database name on which some commands operate by default. This does not limit the databases on which the server will act. Refer to the following dbfilteroption for this.

dbfilter

A regular expression

The expression should match the name of the databases that are considered by the server. If you run the website, it should match a single database, so it will look like ^databasename$. More information on this can be found inChapter 3, Server Deployment.

http_interface

IP address of a network interface

This defaults to 0.0.0.0, which means that the server listens on all interfaces.

http_port

longpolling_port

Port number

These are the ports on which the Odoo server will listen. You will need to specify both to run multiple Odoo servers on the same host; longpolling_portis only used ifworkersis not0.

http_port defaults to 8069 and longpolling_port default to 8072.

logfile

Path to a file

The file in which Odoo will write its logs.

log_level

Log verbosity level

Specifies the level of logging. Accepted values (in increasing verbosity order) include critical,error,warn,info,debug,debug_rpc,debug_rpc_answer,debug_sql.

workers

Integer

The number of worker processes. Refer to Chapter 3, Server Deployment, for more information.

list_db

True/False

Set to True to disable listing of databases. SeeChapter 3, Server Deployment, for more information.

proxy_mode

True/False

Activate reverse proxy WSGI wrappers.Only enable this when running behind atrusted web proxy!

Note

The parsing of the configuration file by Odoo is now using the Python ConfigParsermodule. However, the implementation in Odoo 11.0 has changed, and it is no longer possible to use variable interpolation. So, if you are used to defining values for variables from the values of other variables using the%(section.variable)snotation, you will need to change your habits and revert to explicit values.

Some options are not used in config files, but they are widely used during development:

Options

Format

 

Usage

 

-i or --init

Comma-separated list of module names

It will install given modules by default while initializing the database.

-u or --update

Comma-separated list of module names

It will update given modules when you restart the server. It is mostly used when you modify source code or update the branch from git.

--dev

all, reload, qweb, werkzeug, xml

 

This enables developer mode and the auto-reload feature.

 

 

 

Activating the Odoo developer tools


When using Odoo as a developer, you need to know how to activate developer modein the web interface so that you can access the technical settings menu and developer information. Enabling debug mode will expose several advance configuration options and fields. These options and fields are hidden in Odoo for better usability because they are not used on a daily basis.

How to do it...

To activate developer mode in the web interface, follow these steps:

  1. Connect to your instance and authenticate as admin.
  2. Go to the Settings menu.
  3. Locate the Share the love card, which should be on the right-hand side of the screen:
  4. Click on the Activate the developer mode link.
  5. Wait for the UI to reload.

Note

Alternative way:It is also possible to activate the developer mode by editing the URL. Before the#sign, insert?debug. For instance, if you are starting fromhttp://localhost:8069/web#menu_id=102&action=94, then you need to change this tohttp://localhost:8069/web?debug=#menu_id=102&action=94. Furthermore, if you want debug mode with assets, then change the URLtohttp://localhost:8069/web?debug=assets#menu_id=102&action=94.

To exit developer mode, you can do either of the following:

  • Edit the URL and remove that string
  • Use the Deactivate the developer mode link displayed in the Share the love card when the developer mode is active

Lots of developers are using browser extensions to toggle debug mode. By using this, you can toggle debug mode quickly without accessing the settings menu. These extensions are available for Firefox and Chrome. Take a look at the given screenshot, it will help you to identify the plugin in the Chrome store:

 

How it works...

In developer mode, two things happen:

  • You get tooltips when hovering over a field in a form view or over a column in list view, providing technical information about the field (internal name, type, and so on)
  • A drop-down menu with a Bug icon is displayed next to the user's menu in the top-right corner, giving access to technical information about the model being displayed, the various related view definitions, the workflow, custom filter management, and so on

 

There is a variant of the developer mode: the Developer mode (with assets). This mode behaves like the normal developer mode, but additionally, the JavaScript and CSS code that's sent to the browser is not minified, which means that the web development tools of your browser are easy to use for debugging the JavaScript code (more on this in Chapter 15, Web Client Development).

Note

Caution!

Test your add-ons both with and without developer mode, as the unminified versions of the JavaScript libraries can hide bugs that only bite you in the minified version.

 

Updating Odoo from source


In the first recipe, we saw how to install Odoo from source using the git repository. The main benefit of this setting is being able to update the source code of Odoo using git to get the latest bug fixes.

Getting ready

Stop any instance that's currently running with the Odoo source you are about to update, and then make a backup of all of the databases you care about in case something goes wrong. This is obviously something you need to do for production databases. Refer to the Managing Odoo server databases recipe of this chapter for further instructions.

Next, make a note of the current version of the source you are running. The best way to do this is by creating a lightweight tag using the following command:

$ cd ~/odoo-dev/odoo
$ git checkout 12.0
$ git tag 12.0-before-update-$(date --iso)

How to do it...

To update the source code of Odoo, use the following command:

$ git pull –-ff-only origin 12.0

 

This will fetch the latest version of the source code that's committed to the current branch.

To update an instance running on this code, run the following command:

$ ./odoo-bin -c myodoo.cfg --stop-after-init -u base

Note

-u is the shortcut notation for the --update option of odoo-bin.

If you don't have a database set in the configuration file, you will have to add the-d database_nameoption. This command is to be repeated for all of the instances that are runningwith this version of the source code.

If the update fails, don't panic, because you have backups:

  1. Read the error message carefully and save it to a file, as it will be useful for making a bug report later.
  2. If you cannot figure out what the problem is, restore the service and the Odoo source code to the previous version, which is known to work using the tag you set before updating the source version:
$ git reset --hard 12.0-before-update-$(date --iso)
  1. Drop the broken databases and restore them from the backups you made (refer to the Managing Odoo server databasesrecipe of this chapter for instructions).
  2. Restart your instances and tell your users that the upgrade has been postponed.

Note

Note that, in real life, this should never happen on a production database because you would have tested the upgrade beforehand on a copy of the database, fixed the issues, and only done the upgrade on the production server after ensuring that it runs flawlessly. However, you sometimes still get surprises, so even if you are really sure, make a backup.

 

How it works...

Updating the source code is done by ensuring that we are on the correct branch using git checkoutand then fetching the new revisions usinggit pull. The--ff-onlyoption will cause a failure if you have local commits that aren't present in the remote repository. If this happens and you want to keep your changes, you can use git pull (without--ff-only) to merge the remote changes with yours. If not, usegit reset --hard origin/12.0to force the update, hence discarding your local modifications.

The update command uses the following options:

  • -c: Specifies the configuration file
  • --stop-after-init: Stops the instance when the update is over
  • -u baseor--update base: Requests the update of thebasemodule

When updating a module, Odoo does the following:

  • It updates the database structure for the models defined in the module for which the structure changes. For updates on the stable branch of Odoo, there should be no such changes, but this can happen for your own add-ons or third-party add-ons.
  • It updates the database records that are stored in data files of the module, most notably, the views. It then recursively updates the installed modules that have declared a dependency on the module.

Since the basemodule is an implicit dependency of all Odoo modules, updating it will trigger an update of all of the installed modules in your instance. To update all installed modules, theallaliascan be used instead ofbase.

About the Authors

  • Alexandre Fayolle

    Alexandre Fayolle started working with Linux and free software in the mid 1990s and quickly became interested in the Python programming language. In 2012, he joined Camptocamp to share his expertise on Python, PostgreSQL, and Linux with the team implementing Odoo. He currently manages projects for Camptocamp and is strongly involved in the Odoo Community Association. In his spare time, he likes to play jazz on the vibraphone.

    Browse publications by this author
  • Parth Gajjar

    Parth Gajjar is Application Engineer at Odoo and has been working on Odoo for the past 6 years. For the past year and a half, Parth has been working as a code reviewer at Odoo India. During this time, he has worked in several departments of Odoo, including offshore, migration, and research and development. During his time in research and development, he has developed several key features in Odoo, including the marketing automation module Odoo mobile app (The hybrid JavaScript Part), mobile push notification, Less/CSS editor, Domain Selector widget, and the Qweb report engine prototype. He often gives technical training to Odoo partners. Also, he handes technical interviews at Odoo India.

    Browse publications by this author
  • Holger Brunn

    Holger Brunn has been a fervent open source advocate since he came into contact with the open source market sometime in the nineties. He has programmed for ERP and similar systems in different positions since 2001. For the last 10 years, he has dedicated his time to TinyERP, which became OpenERP and evolved into Odoo. Currently, he works at Therp BV in the Netherlands as a developer and is an active member of the Odoo Community Association (OCA).

    Browse publications by this author
  • Daniel Reis

    Daniel Reis has had a long career in the IT industry, mostly as a consultant implementing business applications in variety of sectors, and today works for Securitas, a multinational security services provider. He has been working with Odoo (formerly OpenERP) since 2010, is an active contributor to the Odoo Community Association projects, is currently a member of the board of the Odoo Community Association, and collaborates with ThinkOpen Solutions, a leading Portuguese Odoo integrator.

    Browse publications by this author

Latest Reviews

(8 reviews total)
很優惠的價格,希望可以常常辦這樣的活動,不過有些檔案太大,不可以傳到kindle有點可惜
The examples provided in the text have errors and it was not possible to receive assistance on the request for clarifications
Technical document and essential issue provided for reader. Thanks

Recommended For You

Book Title
Unlock this full book FREE 10 day trial
Start Free Trial