Odoo 12 Development Essentials - Daniel Reis - E-Book

Odoo 12 Development Essentials E-Book

Daniel Reis

0,0
40,81 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Extend your skills with Odoo 12 to build resourceful and open source business applications




Key Features



  • Explore Odoo 12 capabilities to develop business applications


  • Program business logic and manipulate data to implement specific business rules in your applications


  • Integrate Python APIs for building customizable and scalable business logic





Book Description



Odoo is one of the best platforms for open source ERP and CRM. Its latest version, Odoo 12, brings with it new features and updates in Python packages to develop more customizable applications with additional cloud capabilities.






The book begins by covering the development essentials for building business applications. You will start your journey by learning how to install and configure Odoo, and then transition from having no specific knowledge of Odoo to being ready for application development. You will develop your first Odoo application and understand topics such as models and views. Odoo 12 Development Essentials will also guide you in using server APIs to add business logic, helping you lay a solid foundation for advanced topics. As you progress through the chapters, you will be equipped to build and customize your applications and explore the new features in Odoo 12, such as cloud integration, to scale your business applications. You will get insights into building business logic and integrating various APIs into your application.






By the end of the book, you will be able to build a business application from scratch by using the latest version of Odoo.





What you will learn



  • Manage Odoo server instances


  • Create a new Odoo application from scratch using the most frequently used elements


  • Develop new models and use inheritance to extend existing models


  • Use ORM methods in the Odoo server and from external clients


  • Create Kanban views using QWeb effectively


  • Build custom web and website CMS pages


  • Use external APIs to integrate Odoo with external applications


  • Add automated tests and techniques to debug module business logic





Who this book is for



If you are a developer familiar with Python and MVC design and want to build business applications using Odoo, this book is for you.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 488

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Odoo 12 Development EssentialsFourth Edition

 

 

 

Fast-track your Odoo development skills to build powerful business applications

 

 

 

 

 

 

 

 

Daniel Reis

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Odoo 12 Development Essentials Fourth Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor:Pavan RamchandaniAcquisition Editor: Alok DhuriContent Development Editor: Manjusha MantriTechnical Editor: Abin SebastianCopy Editor: Safis EditingProject Coordinator:Prajakta NaikProofreader: Safis EditingIndexer:Priyanka DhadkeGraphics: Jisha ChirayilProduction Coordinator:Shraddha Falebhai

First published: April 2015 Second edition: November 2016 Third edition: March 2018 Fourth edition: December 2018

Production reference: 1271218

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78953-247-0

www.packtpub.com

 
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Foreword

When I joined Odoo (a long time ago!), my first challenge was to deliver training courses for consultants, including technical sessions for new Odoo developers. Daniel's Odoo Development Essentials is the realization of my wishes from these sessions; the companion book I wish I could have given to the participants to kick-start their first contact with Odoo. Chapter after chapter, he walks you through the creation of your first Odoo app, following best practices at every step. Starting with a solid development environment, you'll soon feel comfortable with your Odoo system, and quickly shape up a typical app. From the model groundwork upwards, you'll learn about each framework layer, including the latest frontend features and the RPC API. In this cloud era, integration is key, and Odoo features a very comprehensive API, opening up endless integration options.

Daniel also includes reference documentation for the most important API areas, and before you know it, you will have grasped the fundamental design properties of Odoo—minimalism, modularity, extensibility, and scalability. Understanding this will be invaluable for any task you set out to accomplish. It is what sets apart good Odoo developers.

Thanks to the yearly updates, the book is great even for more experienced developers, highlighting new features and changes in the Odoo framework. This edition does not fail to deliver, introducing Odoo 12 and the updated API, including coverage of the optimized batch create method, the new super-admin mechanisms, the enhanced debug menu, and much more.

The book also includes a wealth of pro tips, acquired through years of experience, that should make a seasoned Odoo developer out of you in no time, without the extra gray hair! Daniel's natural talent will make you enjoy the Odoo Development Essentials journey!

Olivier Dony R&D Engineer, Odoo Belgium

Contributors

About the author

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 since 2010, is an active contributor to 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.

I would like to thank my wife, Maria, for all her patience and support. My thanks also to Olivier Dony for agreeing to be part of this project and for all the valuable feedback given.

About the reviewer

Parth Gajjar has a degree in computer engineering. He loves programming and designing complex applications in Odoo. He has more than 6 years of experience with Odoo.

In 2012, he joined the Indian branch of Odoo, S.A. He has expertise in both the Python and the JavaScript framework of Odoo. At Odoo, he started working in the offshore department and then moved to R&D department. At Odoo, he has worked on features such as marketing automation, surveys, website forums, Odoo Mobile App, QWeb Report Engine, CSS Editor, and Domain Selector.

Currently, he is active as a code reviewer at Odoo and helps developers with architectural decisions. He often gives technical training to Odoo partners and prospects. He also assists the recruitment department with technical interviews.

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Odoo 12 Development Essentials Fourth Edition

Packt Upsell

Why subscribe?

Packt.com

Foreword

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Quick Start Using the Developer Mode

Technical requirements

Introducing the to-do list project

Basic concepts

The Odoo architecture

Odoo community versus Odoo enterprise

Odoo version policy

Preparing a basic work environment

Using an Odoo SaaS trial database

Installing Odoo on Windows

Installing Odoo using Docker containers

Other installation options

Creating a work database

Enabling the developer mode

Modifying an existing model to add a field

Adding a field to a Model

Adding a field to a form view

Creating a new Model

Configuring access control security

Security groups

Security access control lists

Security record rules

The superuser account

Creating menu items

Creating views

List views

Form views

Search views

Summary

Questions

Preparing the Development Environment

Technical requirements

Setting up a host for the Odoo server

Installing the Windows Subsystem for Linux

Installing a Linux server

Installing Odoo from source

Installing the PostgreSQL database

Installing Odoo system dependencies

Installing Odoo from source

Initializing a new Odoo database

Managing Odoo databases

More server configuration options

Odoo server configuration files

Changing the listening port

Database selection options

Managing server log messages

Installing additional modules

Finding community modules

Configuring the add-ons path

Installing Odoo in a Python virtual environment

Downloading and installing add-on modules from PyPI

The server development mode

Summary

Your First Odoo Application

Technical requirements

Overview of the library project

Creating a new addon module

Preparing the addons path

Creating the module directory and manifest

Adding an icon

Choosing a license

Installing a new module

Upgrading modules

Creating a new application

Adding the app's top menu item

Adding security groups

Adding automated tests

Testing business logic

Testing access security

The model layer

Creating the data model

Setting up access security

Adding access control security

Row-level access rules

The view layer

Adding menu items

Creating the form view

Business document form views

Adding action buttons

Using groups to organize forms

The complete form view

Adding list and search views

The business logic layer

Adding business logic

Web pages and controllers

Summary

Questions

Further Reading

Extending Modules

Technical requirements

Learning project – extending the Library app

In-place Model extension

Adding fields to a Model

Modifying existing fields

Modifying Views and data

Extending Views

Selecting extension points with XPath

Modifying data

More Model inheritance mechanisms

Copying features with prototype inheritance

Embedding Models using delegation inheritance

Extending Models using mixin classes

Extending Python methods

Extending web controllers and templates

Extending Web Controllers

Extending QWeb Templates

Summary

Questions

Further reading

Import, Export, and Module Data

Technical requirements

Understanding the external identifier concept

How external identifiers work

Finding external identifiers

Exporting and importing CSV data files

Exporting data

Importing data

Related records in CSV data files

Adding module data

Demonstration data

Using XML data files

The noupdate data attribute

Defining records in XML

Setting field values directly

Setting values using expressions

Setting values on many-to-one relation fields

Setting values on to-many relation fields

Shortcuts for frequently used models

Other actions in XML data files

Deleting records

Calling model methods

Summary

Questions

Further reading

Models – Structuring the Application Data

Technical requirements

Learning project – improving the Library app

Creating models

Model attributes

Models and Python classes

Transient and abstract models

Inspecting existing models

Creating fields

Basic field types

Common field attributes

Special field names

Relationships between models

Many-to-one relationships

One-to-many inverse relationships

Many-to-many relationships

Hierarchical relationships

Flexible relationships using Reference fields

Computed fields

Searching and writing to computed fields

Storing computed fields

Related fields

Model constraints

SQL model constraints

Python model constraints

About the Odoo base Models

Summary

Recordsets – Working with Model Data

Technical requirements

Using the shell command

The execution environment

Environment attributes

The environment context

Modifying the recordset execution environment

Querying data with recordsets and domains

Creating recordsets

Domain expressions

Accessing data on recordsets

Accessing data on records

Accessing relational fields

Accessing date and time values

Converting text-represented dates and times

Writing on records

Writing with object-style value assignment

Writing with the write() method

Writing date and time values

Creating and deleting records

Composing recordsets

Low-level SQL and database transactions

Summary

Business Logic – Supporting Business Processes

Technical requirements

Learning project – the library_checkout module

Using stages for document-centered workflows

The ORM method decorators

Methods for recordsets – @api.multi

Methods for singleton records – @api.one

Class static methods – @api.model

On change methods

Other model method decorators

Using the ORM built-in methods

Methods for writing model data

Methods for data import and export

Methods to support the user interface

The message and activity features

Message subtypes

Posting messages

Adding followers

Creating a wizard

The wizard model

The wizard form

The wizard business logic

Using log messages

Raising exceptions

Unit tests

Adding unit tests

Running tests

Setting up tests

Writing test cases

Testing exceptions

Development tools

Server development options

Debugging

The Python debugger  

A sample debugging session

Alternative Python debuggers

Printing messages and logging 

Inspecting and killing running processes

Summary

Further reading

External API – Integrating with Other Systems

Technical requirements

Learning project – a client to catalogue books

Setting up Python on the client machine

Connecting to Odoo API using XML-RPC

Running server methods using XML-RPC

Search and read API methods

The Library client XML-RPC interface

The Library client user interface

Using the OdooRPC library

About the ERPpeek client

Summary

Further reading

Backend Views – Designing the User Interface

Technical requirements

Menu items

Window Actions

Form view structure

Business document views

The header

Header buttons

The stage pipeline

Using states instead of stages

The document sheet

Title and subtitle

Grouping the form content

Tabbed notebooks

Fields

Labels for fields

Field widgets

Relational fields

Buttons

Smart buttons

Dynamic view elements

On-change events

Dynamic attributes

List views

Search views

Other view types

Activity views

Calendar views

Pivot views

Graph views

Summary

Further reading

Kanban Views and Client-Side QWeb

Technical requirements

About Kanban boards

Kanban views

Designing Kanban views

Priority, Kanban state, and color

Kanban card elements

The Kanban card layout

Adding a Kanban card option menu

Actions in Kanban views

The QWeb template language

The QWeb JavaScript evaluation context

Dynamic attributes by string substitution – t-attf

Dynamic attributes by expressions – t-att

Loops – t-foreach

Conditionals – t-if

Rendering values – t-esc and t-raw

Set values on variables – t-set

Call and reuse other templates – t-call

Dynamic attributes using dictionaries and lists

Inheritance on Kanban views

Custom CSS and JavaScript assets

Summary

Further reading

Reports and Server-Side QWeb

Technical requirements

Installing wkhtmltopdf

Creating business reports

QWeb report templates

Presenting data in reports

Rendering images

Report totals

Defining paper formats

Enabling language translation in reports

Reports based on custom SQL

Summary

Further reading

Creating Website Frontend Features

Technical requirements

Learning project – the Library self-service

Our first web page

Hello World using a QWeb template

HelloCMS!

Building websites

Adding CSS and JavaScript assets

The checkout-list controller

The checkout QWeb template

The checkout detail page

Summary

Further reading

Deploying and Maintaining Production Instances

Technical requirements

Installing Odoo from source code

Installing dependencies

Preparing a dedicated system user

Installing from the source code

Setting up the configuration file

Multiprocessing workers

Setting up Odoo as a system service

Creating a systemd service

Creating an Upstart or sysvinit service

Checking the Odoo service from the command line

Setting up an nginx reverse proxy

Configuring and enforcing HTTPS

Creating a self-signed SSL certificate

Configuring HTTPS access on nginx

Caching static content

Server and module updates

Creating a staging environment

Updating Odoo source code

Summary

Further reading

Assessments

Chapter 1

Chapter 3

Chapter 4

Chapter 5

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Odoo is a fully-featured open source platform for building applications. Based on this core framework, a suite of integrated applications was built, covering all business areas from CRM and sales to stocks and accounting.

Beyond these out-of-the-box features, Odoo's framework was built with extensibility in mind. Modifications can be implemented as extension modules, to be applied as a layer on top on the existing modules being changed, without actually changing the original code. This provides a clean and easy-to-control customization approach.

This capability to combine several modules into feature-rich applications, along with the open source nature of Odoo, are probably important factors in the growth of the community around Odoo. In fact, there are thousands of community modules available for Odoo covering virtually every topic, and the number of people getting involved has been steadily growing every year.

Odoo 12 Development Essentials provides a step-by-step guide to Odoo development, allowing readers to quickly climb the learning curve and become productive in the Odoo application platform. At the same time, it tries to provide good reference materials, to be kept close to hand every time you are working with Odoo.

Who this book is for

This book was written for developers with minimal programming knowledge but a strong will to learn. We will often use the Python language and explain how to run Odoo in an Ubuntu/Debian system, but little previous knowledge of them is assumed. The code examples are kept simple and clear, and they are accompanied by appropriate explanations.

Experienced developers who are already familiar with Odoo should also benefit from this book. Not only does it allow them to consolidate their knowledge, but it also provides an easy way to get up to date with all the details that changed with Odoo 12.0. In fact, special care was taken to highlight all the relevant changes between the different Odoo versions since 8.0.

Finally, this book should provide a solid reference to be used daily, both by newcomers and experienced developers. The documentation of the relevant differences between the several Odoo versions should also be a good resource for any developer working with different Odoo versions at the same time or who is porting modules to other versions.

What this book covers

This books contains 14 chapters, organized into five parts: introduction, models, business logic, views, and deployment.

The first part introduces the Odoo framework, explains how to set up your development environment, and provides a tutorial including a thorough, step-by-step creation of a new Odoo module:

Chapter 1, Quick Start Using the Developer Mode, visually introduces the Odoo development concepts by walking through the creation of an Odoo application directly from the user interface, a simple to-do tracking application. Instructions are given to set up Odoo in our workstation, but an existing Odoo installation, or an Odoo.com instance, can be used, so no local setup is required.

Chapter 2, Preparingthe Development Environment, explains how to install Odoo from source code and how to set up the development environment to be used throughout the book. We choose to install Odoo in an Ubuntu environment, and, with Windows 10, we can use the Windows Subsystem for Linux (WSL) to achieve this.

Chapter 3, Your First Odoo Application, provides a step-by-step guide to the creation of our first Odoo module, a book catalog for a Library app. While the example is simple, it covers all the different layers and components that can be involved in an Odoo application: models, business logic, backend views, and web frontend views.

Chapter 4, Extending Modules, explains the available inheritance mechanisms and how to use them to create extension modules, adding or modifying features from other existing add-on modules.

 

The second part of the book introduces the models responsible for the data model structures around which the application is built:

Chapter 5, Import, Export, and Module Data, addresses the usage of data files in Odoo and their role in modules to load data and configurations to the database. It covers the XML and CSV data file formats, the external identifier concept, how to use data file in modules, and data import/export operations.

Chapter 6, Models – Structuring the Application Data, discusses the model layer in detail, introducing the framework's Object-Relational Mapping (ORM), the different types of models available, and the field types, including relational and computed fields.

In the third part, we explain how to write the business logic layer on top of the models—the controller component of the architecture. This includes the built-in ORM functions, used to manipulate the data in the models, and social features used for messages and notifications:

Chapter 7, Recordsets – Working with Model Data, introduces the concepts and features of ORMs, how to query and ready to read data from models, how to manipulate recordsets, and how to write changes on model data.

Chapter 8, Business Logic – Supporting Business Processes, explores programming business logic on the server side to manipulate data and implement specific business rules. It also explains how to use wizards for more sophisticated user interaction. The built-in social features, messages, chatter, followers, and channels, are addressed, as well as testing and debugging techniques.

Chapter 9, External API – Integrating with Other Systems, shows how to implement external Odoo applications by implementing a command-line client that interacts with our Odoo server. There are several alternative client programming libraries available, which are introduced and used to implement our showcase client utility.

The fourth part explores the view layer and the several technologies that can be used for the user interface:

Chapter 10, Backend Views – Design the User Interface, covers the web client's view layer, explaining the several types of views in detail and all the elements that can be used to create dynamic and intuitive user interfaces.

Chapter 11, Kanban Views and Client-Side QWeb, keeps working with the web client, but introduces Kanban views and explains the QWeb templates used to design the Kanban board elements.

Chapter 12, Reports and Server-Side QWeb, discusses using the QWeb-based report engine and everything needed to generate printer-friendly PDF reports.

Chapter 13, Creating Website Frontend Features, introduces Odoo website development, including web controller implementations and using QWeb templates to build frontend web pages.

Finally, the fifth part covers deployment and maintenance practices. Some special considerations, not relevant to development environments, need to be taken into account when deploying for production use:

Chapter 14, Deploying and Maintaining Production Instances, shows us how to prepare a server for production use, explaining what configuration should be taken care of and how to configure an NGINX reverse proxy for improved security and scalability.

By the end of the book, the reader should have a solid understanding of all the steps and components involved in the Odoo application development cycle, from the drawing board to the production, deployment, and maintenance of these applications.

To get the most out of this book

Odoo is built using the Python programming language, so it is a good idea to have a good knowledge of it. We also choose to run Odoo in an Ubuntu host, and will do some work on the command line, so it will help to be familiar with it.

To get the most out of this book, we recommend that you do some complementary reading on the Python programming language, the Ubuntu/Debian Linux operating system, and the PostgreSQL database.

While we will run Odoo in an Ubuntu host (a popular cloud hosting option), we will provide guidance on how to set up our development environment in a Windows system using the Windows for Linux Subsystem (WSL), available in recent Windows 10 builds. Of course, working from an Ubuntu/Debian native system is also a good choice.

All the required software is freely available, and the instructions on where to find it will be given.

Download the example code files

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

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Odoo-12-Development-Essentials-Fourth-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789532470_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The ~ symbol is a shortcut for the user's home directory, such as /home/daniel."

A block of code is set as follows:

<search> <filter name="item_not_done" string="Not Done" domain="[('x_is_done', '=', False)]" /></search>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<search> <filter name="item_not_done" string="Not Done"

domain="[('x_is_done', '=', False)]"

/></search>

Any command-line input or output is written as follows:

$ createdb MyDB

$ createdb --template=MyDB MyDB2

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Click on the debug icon and select the Edit Action option. This will open the Window Actions used to open the current Views."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packt.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Quick Start Using the Developer Mode

Odoo provides a rapid application development framework that's particularly suited to building business applications. This type of application is usually concerned with keeping business records, centered around create, read, update, and delete (CRUD) operations. Not only does Odoo makes it easy to build this type of application, it also provides rich components to create compelling user interfaces, such as kanban, calendar, and graph views.

This book is organized into five parts. We start by providing an overview of the Odoo framework, setting up a development environment, and building our first Odoo application. Being generally familiar with the main Odoo components, we will dive, in more detail, into each of the three main application layers—models, business logic, and views. Finally, our application will need to be deployed to a production environment and maintained. That's what is covered in the final chapter of the book.

In this chapter, we will quickly get into the action, exploring the Odoo internals directly from the web user interface, even before having set up our local development environment.

In this chapter, we will do the following:

Introduce the learning project used in this chapter, the to-do application.

Understand the Odoo architecture, editions, and releases, to have the essential context and insights relevant to working with Odoo.

Prepare a basic Odoo work environment, so that we can work on an example project and learn by experience. Several options are proposed:

Using Odoo online

Using the Windows all-in-one installer

Using Docker

Enable the developer mode, to make available in the user interface the tools we will be using.

Modify an existing model to add a field, a quick introduction to a common customization.

Create a custom data model, to add new data structures for your applications.

Configure access security, to allow specific user groups to access the application features.

Create menu items, to make the new data model available in the user interface.

Create list, form, and search views, the basic building blocks for the user interface.

We will learn by example, and the next section will introduce the project we will use for this.

Technical requirements

The minimal requirement for this chapter is to have a modern web browser, such as Firefox, Chrome, or Edge. With this you can follow the chapter using an Odoo SaaS trial database, as explained in the Preparing a basic work environment section.

You may go a little further and use a packaged Odoo distribution to have it locally installed on your computer. For that, you only need an operating system such as Windows, macOS, Debian-based Linux (such as Ubuntu), or Red Hat-based Linux (such as Fedora). Windows, Debian, and Red Hat have installation packages available. Another option is to use Docker, available for all these systems and for macOS. The Preparing a basic work environment section will guide us in any of these installation scenarios.

In this chapter, we will mostly have point-and-click interaction with the user interface. You will find the code snippets used and a summary of the steps performed in the book's code repository, at https://github.com/PacktPublishing/Odoo-12-Development-Essentials-Fourth-Edition, under the ch01 folder.

Introducing the to-do list project

The TodoMVC (http://todomvc.com/) project provides a comparison between multiple JavaScript frameworks by implementing the same simple to-do application in each of them. Inspired by this, we will go through the experience of building a simple to-do application with Odoo.

It should allow us to add new to-do items, and then mark them as completed. For example, you could add to-do items to the list, such as Buy eggs, and then check an Is Done? box once they are completed. The To-do Items should be private to the current user, so that you will only be able to access your own to-do items.

This should be enough for a simple to-do application, but to make it a little more interesting we will introduce a couple of complications. Our to-do list items should be able to include a list of people involved in the task, the work team.

It is useful to think about our application by considering several layers involved:

The data tier

: Implemented through models

The logic tier

: Implemented through automation code

The presentation tier

: Implemented through views

For the data tier, we need a To-do Item model. We will also make use of the built-in partner (or contacts) model to support the work team feature. We must not forget to configure the access control security for our new model.

The logic tier used here will be the basic CRUD operations handled by the framework, and we don't have in our requirements any additional automation to support. To access the full power of the framework, we need to use Python code in developer modules. While we can't do that yet, the developer menu does provide some tools for us to implement some business logic from the user interface, the automate actions. We will work on a simple example of how to use them.

Finally, for the presentation tier we will add the menu option for our application, and the views for the to-do item model. The essential views for a business application are the list view, where we can browse the existing records, and the form view, where we can zoom in to a record and see all the details. For better usability, we can also add preconfigured filters to the search box, available in the list view. The available search options are also considered a view, so this can be done through a search view.

The following are the steps to create a to-do list:

First, we will create a new model for to-do items, and then make it available to users by adding a to-do top menu for it.

Next, we will create the list and form views for the

To-do Items

model. This new model should have these fields:

Description

 text field

Is Done?

 flag (a Boolean field)

Our specification for the application includes the ability to select a list of people that will be working on the task, so we need a Model to represent people. Fortunately, Odoo includes out of the box a model for this—the partner model (res.partner is its technical name), used to store individual people, companies, and addresses.

And only particular persons are selectable for this work team. This means that we need to modify the partner model to add this new Is Work Team? flag.

So, the To-do Items model should also include the work team field, with a list of people. The linked people are selectable from the partners/contacts that have the Is Work Team? flag enabled.

As a summary, this is what we will need to do:

Add a field to the partner model and form view

Create a

To-do Item

model

Create a to-do application menu item

Create a to-do Item user interface

: List and form view, and UI search options

Create access security

:

Group

,

access control lists

(

ACL

), and

Record Rules

Before we go into the actual implementation, we will first discuss a few basic concepts about the Odoo framework, and then learn how to prepare an environment to work with.

Basic concepts

It is useful to understand the several layers involved in the Odoo architecture, and the role of each type of component we will use. So we will have a pragmatic overview of the Odoo application architecture, with a focus on helping application development by decomposing work into several components.

Also, Odoo publishes two different product editions, community and enterprise, and regularly releases new versions for both. It is important to understand the differences we can expect between the editions, and what a new major release can mean for our development and deployment. For this, we have an overview of the differences between CE and EE, and on the Odoo major version stability policy.

Let's start looking at the Odoo application architecture.

The Odoo architecture

Odoo follows a multi-tier architecture, and we can identify three main tiers—data, logic, and presentation:

The Data Tier is the lowest-level layer, and is responsible for data storage and persistence. Odoo relies on a PostgreSQL server for this. PostgreSQL is the only supported database server, and this is a design choice. So, other databases such as MySQL are not supported. Binary files, such as attachments of documents or images, are usually stored in the filesystem, in a directory referred to as the filestore.

This means that a full backup of an Odoo instance needs both a database dump and a copy of the filestore.

The Logic Tier is responsible for all the interactions with the data layer, and is handled by the Odoo server. As a general rule, the low-level database should only be accessed by this layer, since it is the only way to ensure security access control and data consistency. At the core of the Odoo server, we have the object-relational mapping (ORM) engine for this interface. The ORM provides the application programming interface (API) used by the add-on modules to interact with the data.

For example, the partner data entity, such as a customer or a supplier, is represented in the ORM by a model. This model is a Python object class supporting several interaction methods, such as create() to create new partner records, or read() to query existing records and their data. These generic methods can implement specific business logic in particular models. For example, the create() method might implement default values or enforce validation rules; the read() method might support some automatically computed fields, or enforce access controls depending on the user performing that action.

The Presentation Tier is responsible for presenting data and interacting with the user. It is implemented by a client responsible for all the user experience. The client interacts with the ORM API to read, write, verify, or perform any other action, calling ORM API methods through remote procedure calls (RPCs). These are sent to the Odoo server for processing, and then the results are sent back to the client for further handling.

For the Presentation Tier, Odoo provides a full-featured web client out of the box. The web client supports all the features needed by a business application: login sessions, navigation menus, data lists, forms, and so on. The global look and feel are not as customizable as a frontend developer might expect, but it makes it easy to create a functional and consistent user experience.

A complementary presentation layer includes the website framework. It gives full flexibility to create web pages with the exact user interface intended, like in other CMS frameworks, at the expense of some additional effort and web expertise. The website framework supports web controllers to implement code for presenting specific logic, keeping it separate from the model's intrinsic logic. Frontend developers will probably feel very much at home in this space.

The Odoo server API is very open, and all server functions are available through it. The server API used by the official web client is the same as the one available to any other application. So, other client implementations are possible, and could be built in almost any platform or programming language. Desktop and smartphone applications can be built to provide specific user interfaces, leveraging the Odoo data and logic tiers for business logic and data persistence.

Odoo community versus Odoo enterprise

Odoo is the name of the software product, and also the name of the company that builds it. Odoo follows an open core business model, where the community edition (CE) is free and open source, and the enterprise edition (EE) is a paid product, providing income for the company.

The CE provides all the framework features plus the essential features for most of the business applications bundled with Odoo. It is licensed under an LGPL license, chosen to allow adding proprietary extensions on top of open source modules.

The EE is built on top of the CE, providing all its features plus some additional exclusive ones. Notably, it includes an improved and mobile-friendly user interface, although the user interface underlying the organization is essentially the same in both editions.

The Odoo online SaaS service uses Odoo enterprise, and may have deployed intermediate versions released after the latest Odoo enterprise major version.

Odoo version policy

At the time of writing, Odoo's latest stable version is version 12, marked on GitHub as branch 12.0. This is the version we will work with throughout the book. In recent years, major stable versions have been released on a yearly schedule, in October, at the annual Odoo experience conference.

The last three stable versions are supported. With the release of 12.0, versions 11.0 and 10.0 are still supported, and version 9.0 stopped being supported. This means it will stop receiving bug and security fixes.

It's important to note that Odoo databases are incompatible between Odoo major versions. If you run an Odoo 11 server against a database created for a previous major version of Odoo, it won't work. Non-trivial migration work is needed before a database can be used with a later version of the product.

The same is true for add-on modules: as a general rule, an add-on module developed for an Odoo major version will not work on other versions. When downloading a community module from the web, make sure it targets the Odoo version you are using.

On the other hand, major releases (10.0, 11.0) are expected to receive frequent updates, but these should be mostly bug fixes. They are assured to be API-stable, meaning that model data structures and view element identifiers will remain stable. This is important because it means there will be no risk of custom modules breaking due to incompatible changes in the upstream core modules.

The version in the master branch will result in the next major stable version, but until then, it's not API-stable and you should not use it to build custom modules. Doing so is like moving on quicksand—you can't be sure when some changes will be introduced that will break your custom module.

Preparing a basic work environment

The first thing we need is to have an Odoo instance that we can use for our learning project.

For the purpose of this chapter, we just need a running Odoo instance, and the particular installation method is not relevant. To quickly get up and running, we can use a prepackaged Odoo distribution, or even just use an Odoo SaaS trial database (https://www.odoo.com/).

Using an Odoo SaaS trial database

This can be the simplest way to get started. No need to actually install anything for now, just go to https://www.odoo.com/ and create a free trial database. The Odoo Cloud software as a service (SaaS) is based on the enterprise edition (EE), with additional, exclusive, intermediate version releases. Other than the trial, at the time of writing it also offers a free plan: databases with only one application installed are free to use. The SaaS service runs vanilla Odoo enterprise and custom modules are not allowed. For cases where customizations are needed, the Odoo.sh service can be used, providing a full-featured development platform to customize and host solutions based on Odoo enterprise. See https://www.odoo.sh/ for more information.

Changes in Odoo 12In previous Odoo versions, the menu structure of the web client was significantly different between the CE and EE. In Odoo 12, the menus in both editions follow a similar structure.

To create a new database on the Odoo Cloud SaaS, you will probably be asked to select a starting application. No specific application is required to follow this chapter, but if you're unsure on what to pick, customer relationship management (CRM) would be fine.

Also worthy of note is that the EE, on the Odoo SaaS, has the Odoo Studio application builder available. We won't be using it, since it is not available for the CE, which is used as a reference in this book. Odoo Studio provides a user-friendly user interface for the developer features introduced in this chapter, along with a few extra features, such as the ability to export the customizations made in a convenient module package. But the main capabilities are similar to what we can get by using the basic developer mode.

Installing Odoo on Windows

Ready-to-install Odoo packages can be found at https://download.odoo.com, available for any of the currently supported Odoo versions, as well as for the master branch (the latest development version). You can find the Windows (.exe) installers, alongside the Debian (.deb) and CentOS (.rpm) packages.

To install on Windows, find the latest .exe build in the nightly directory and install it. The all-in-one installation is straightforward, as it provides all that you will need to run Odoo; Python 3, a PostgreSQL database server, the Odoo server, and all Odoo additional dependencies. A Windows service is also created to automatically start the Odoo and PostgreSQL services when your machine starts.

Installing Odoo using Docker containers

Docker provides a convenient multi-platform solution to run applications. It can be used to run applications on macOS, Linux, and Windows. The container technology is simple to use and resource-efficient when compared to classic virtual machines.

You must first have Docker installed in your system. The Docker CE is free of charge, and can be downloaded from https://www.docker.com. It's worth referring to Docker's website for the latest installation details.

In particular, keep in mind that virtualization must be enabled in your BIOS setup. Also, the Docker CE for Windows requires Hyper-V, only available in Windows 10 Enterprise or Education releases (see https://docs.docker.com/docker-for-windows/install), and Docker CE for mac requires OS X El Capitan 10.11 and newer macOS releases.

For other Windows and macOS versions, you should instead install Docker Toolbox, available at https://docs.docker.com/toolbox/overview. Docker Toolbox bundles VirtualBox and provides a preconfigured shell that should be used as the command-line environment to operate Docker containers.

The Odoo Docker images are available in the Docker store at https://store.docker.com/images/odoo. There, we can find the versions available, and the basic instructions to get started with them. To run Odoo, we will need two Docker containers, one for the PostgreSQL database, and another for the Odoo server.

The installation and operation is done from a command-line window. To install the PostgreSQL Docker container, run this:

$ docker run -d -e POSTGRES_USER=odoo -e POSTGRES_PASSWORD=odoo --name db postgres:10

It will download the latest PostgreSQL image from the internet, and start a container for it running as a background job.

Next, install and run the Odoo server container, linking it to the PostgreSQL container we just started, and exposing it on port 8069:

$ docker run -t -p 8069:8069 --name odoo --link db:db odoo:12.0 -d odoo12

With this, you will see the live Odoo server log in your terminal window, and can access the Odoo instance by opening http://localhost:8069 with your favorite web browser.

The Odoo server can fail to start if port 8069 is already in use, for example, by an already running Odoo server. In this case, you might look for and stop the running service (for example, by looking at the list of running services), or try to start this Odoo server on a different port by changing the-poption. For example, to use port 8070, use -p 8070:8069. In that case, you probablyalso want to change-d <dbname>to set the database name that instance should use.

There are a few basic commands you should know to help manage these Docker containers:

docker stop <name>

stops a container

docker start <name>

starts a container

docker start -a <name>

starts a container, and attaches the output, such as the server log, to the terminal window

docker attach <name>

reattaches a container's output to the current terminal window

docker ps

lists the current Docker containers

These are the basic commands needed to operate our Docker containers.

In case you get in trouble running the containers, here is a recipe to start over:

$ docker container stop db

$ docker container rm db

$ docker container stop odoo

$ docker container rm odoo

The Docker technology has more potential, and it might be interesting to learn more about it. The Docker website has good learning documentation. A good place to get started is https://www.docker.com/get-started.

Other installation options

It is worth noting that installation packages are also available for Debian-based (such as Ubuntu) and Red Hat-based (such as CentOS and Fedora) Linux systems.

We won't be able to go into much detail on how to install them, but if you are familiar with Debian or Red Hat, this is also an option to consider. The installation packages are available from https://download.odoo.com, and the official documentation provides a good explanation on how to install them at https://www.odoo.com/documentation/master/setup/install.html.

Regarding the source code installation, it is the most complex, but also the most versatile of the installation alternatives, and it will be explained in detail in Chapter 2, Preparing the Development Environment.

Enabling the developer mode

To implement our project, we need the tools provided by the developer mode, which needs to be enabled.

The developer mode allows us to customize Odoo apps directly from the user interface. This has the advantage of being a rather quick way to make changes and add features. It can be used from small modifications, such as adding a field, to larger customizations, such as creating an application with several models, views, and menu items.

These customizations done directly from the user interface have some limitations, when compared to the customizations done with programming tools, covered throughout the rest of the book. For example, you can't add or extend the default ORM methods (although in some cases automated actions can be enough to provide an alternative to that). They also can't be easily integrated into a structured development workflow, which typically involves version control, automated tests, and deploying into several environments, such as quality assurance, pre-production, and production.

Here, we will be using the developer mode features mainly as a way to introduce how application configuration data is organized in the Odoo framework, and how the developer mode can be leveraged for simple customizations, or to quickly outline or prototype the solution to implement.

To enable the developer mode, go to Settings | Dashboard, and in the lower-right corner you should find the Activate the developer mode link. Clicking on it enables the developer mode features for this browser window. For Odoo 9.0 and before, the developer mode is activated in the About dialog window, available from the User menu, in the upper-right corner of the web client. 

We also have available an Activate the developer mode (with assets) option. What it does is prevent web client asset minification. It is useful to debug the web client itself, at the expense of making the navigation a little slower.

For faster load times, the web client minifies the JavaScript and CSS assets into compact files. Unfortunately, that makes web client debugging nearly impossible. The Activate the developer mode (with assets) option prevents this minification and loads the web assets in individual, non-minified files.

The developer mode can also be enabled by tinkering directly with the current URL, so that you don't have to leave your current screen to open settings. Edit the URL to change the .../web#... part to insert .../web?debug#... or .../web?debug=assets#.... For example, http://localhost:8069/web#home would be changed to http://localhost_8069/web?debug#home.

Although there is no link to enable it, the frontend framework also supports the debug flag. To disable asset minification in a frontend web page, add ?debug=assets to the corresponding URL. Take note that the option will probably not persist when navigating through links to other frontend pages.

There are browser extensions available for both Firefox and Chrome that provide a convenient button to enable and disable the developer mode. Look for "Odoo debug" in Firefox add-ons or the Chrome store.

Once the developer mode is enabled, we will see two additional menus available:

The

Developer Tools

menu, the bug icon on the right-hand side of the top menu bar, just before the username and avatar

The

Technical

menu item, in the

Settings

application

The following screenshot shows the two additional menus:

The developer mode also enables additional information on form fields; when pausing the mouse pointer over a field, a tooltip will display technical information on it.

We will be using the most relevant developer mode features in the next sections.

Modifying an existing model to add a field

Adding a custom field to an existing form is a common customization, and it can be done from the user interface, without the need to create a custom module.

For our to-do application, we want to select a group of people that will be able to collaborate on to-do items. We will identify them by setting a flag on their partner form. For that, we will add an Is Work Team? flag to the partner model.

The partner model is part of the Odoo core, and is available even if you haven't installed any apps yet. However, you may not have a menu option available to visit it. A simple way to add one is to install the Contacts application. Open the Apps top menu, look up this application, and install it, if you have not already done so:

After this, the Contacts application top menu option will be available.

Adding a field to a Model

To visit a Model's definition, with the developer mode enabled, in the Settings application go to the Technical | Database Structure | Models menu item.

Look up the Model having res.partner. The corresponding Model Description should be Contact. Click on it to open the form view, and you will see all the specific details about the partner model, including the field list:

Now, Edit the form and click on the Add a line button at the bottom of the Fields list. A pop-up window will be presented for new field creation.

Let's fill in the configuration:

Field Name

:

x_is_work_team

Field Label

:

Is Work Team?

Field Type

:

b

oolean

The Field Name must start with x_. This is mandatory for Models and Fields created directly through the user interface. Customizations made through add-on modules don't have this limitation.

That's it. Click save and close, and our new field should have been added to the Fields list. Chances are that this model has more than 80 fields, and so you might need to navigate to the next page of the Fields list to see it. To do so, use the right arrow in the upper-left corner of the Fields list.

Now, click on the upper-left save button to make this change permanent.

Adding a field to a form view

Our new field is now available in the partners model, but it is not yet visible to users. For that, we need to add it to the corresponding views.

Still on the Model havingres.partner form, click on the Views