35,99 €
Fast track your development skills to build resourceful, open-source business applications with Odoo 11
Odoo continues to gain worldwide momentum as the best platform for open source ERP installations. Now, with Odoo 11, you have access to an improved GUI, performance optimization, integrated in-app purchase features, and a fast-growing community to help transform and modernize your business. With this practical guide, you will cover all the new features that Odoo 11 has to offer to build and customize business applications, focusing on the publicly available community edition.
We begin with setting up a development environment, and as you make your way through the chapters, you will learn to build feature-rich business applications. With the aim of jump-starting your Odoo proficiency level, from no specific knowledge to application development readiness, you will develop your first Odoo application. We then move on to topics such as models and views, and understand how to use server APIs to add business logic, helping to lay a solid foundation for advanced topics.
The book concludes with Odoo interactions and how to use the Odoo API from other programs, all of which will enable you to efficiently integrate applications with other external systems.
Odoo 11 Development Essentials caters to developers who are familiar with Python and MVC design and now want to build effective business applications using Odoo.
Daniel Reis has had a long career in the IT industry, most 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.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 406
Veröffentlichungsjahr: 2018
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: Aaron LazarAcquisition Editor:Larissa PintoContent Development Editor:Flavian VazTechnical Editor: Sachin SunilkumarCopy Editor: Safis EditingProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics:Jason MonteiroProduction Coordinator: Aparna Bhagat
First published: April 2015 Second edition: November 2016 Third edition: March 2018
Production reference: 1230318
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78847-779-6
www.packtpub.com
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.
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
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.PacktPub.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.PacktPub.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.
Daniel Reis has had a long career in the IT industry, most 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.
Olivier Dony is a Belgian engineer specialized in network engineering, databases, and information security. He enjoys analyzing and solving complex problems and getting to the bottom of seemingly inexplicable bugs.
He joined Odoo Belgium in 2009, where he had the chance to take on many roles, such as working with the community, running the cloud platform with his team, setting up the security response team, or just as importantly, solving interesting problems everyday within the Odoo R&D.
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.
Title Page
Copyright and Credits
Odoo 11 Development Essentials Third Edition
Packt Upsell
Why subscribe?
PacktPub.com
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
Conventions used
Get in touch
Reviews
Quick Start – The Odoo Developer Mode and Concepts
The Odoo architecture
The Developer mode
Introducing the Library project
Creating a work database
Enabling the developer tools
Adding a field to an existing Model
Adding Menus, Models, and Views
Creating menus
Creating a Custom Model
Creating Views
Configuring access control security
About Odoo base Models
Summary
Installing and Organizing the Development Environment
Setting up a host for the Odoo server
Using a virtual machine
Installing a Linux server
Installing Odoo from source
Initializing a new Odoo database
Managing Odoo databases
A word about Odoo product versions
More server configuration options
Odoo server configuration files
Changing the listening port
The database filter option
Managing server log messages
Developing from a remote workstation
Using a Linux text editor
Installing and configuring Samba
Installing additional modules
Finding community modules
Configuring the addons path
Updating the apps list
Summary
Your First Odoo Application – A Practical Overview
Creating a new addon module
Creating the module's basic skeleton
Adding an icon
A word about licenses
Discovering and installing new modules
Adding to the addons path
Installing the new module
Upgrading a module
The server development mode
The model layer
Creating the data model
Extending existing models
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
Extending views
The business logic layer
Adding business logic
Extending Python methods
Adding automated tests
Testing business logic
Testing access security
Setting up access security
Adding access control security
Row-level access rules
Web pages and controllers
Summary
Models – Structuring the Application Data
Organizing application features into modules
Introducing the todo_stage module
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
Extending models
Adding fields to a model
Modifying existing fields
Relationships between models
Many-to-one relationships
Many-to-many relationships
One-to-many inverse relationships
Hierarchical relationships
Dynamic relationships using Reference fields
Computed fields
Searching and writing to computed fields
Storing computed fields
Related fields
Model constraints
More model inheritance mechanisms
Copying features with prototype inheritance
Embedding models using delegation inheritance
Summary
Import, Export, and Module Data
Understanding external identifiers
Finding external identifiers
Exporting and importing data
Exporting data
Importing data
Related records in CSV data files
Module data
Demonstration data
XML data files
The noupdate data attribute
Defining records in XML
Setting field values
Setting values using expressions
Setting values for relation fields
Shortcuts for frequently used models
Other actions in XML data files
Deleting records
Triggering functions
Modifying data
Summary
The ORM API – Handling Application Data
Understanding the ORM decorators
Record handling decorators
Specific purpose decorators
Using the ORM built-in methods
Methods for writing model data
Methods for web client use over RPC
Methods for data import and export
Methods for the user interface
The Mail and Social features API
Message subtypes
Posting messages
Adding followers
Summary
Business Logic – Supporting Business Processes
Creating a wizard
The wizard model
The wizard form
The wizard business logic
Logging
Raising exceptions
Helper actions in wizards
Working with the ORM API
The shell command
The server environment
Modifying the execution environment
Transactions and low-level SQL
Context and domain
Context data
Domain expressions
Working with recordsets
Querying models
Singletons
Writing on records
Working with time and dates
Operations on recordsets
Manipulating recordsets
Using relational fields
Working with relational fields
Summary
External API – Integrating with Other Systems
Setting up a Python client
Calling the Odoo API using XML-RPC
Opening an XML-RPC connection
Reading data from the server
Calling other methods
Writing a To-Do client application
Communication layer with Odoo
Creating the CLI
Introducing the ERPpeek client
The ERPpeek API
The ERPpeek CLI
Introducing the OdooRPC library
Summary
Backend Views – Design the User Interface
Defining the user interface with XML files
Menu items
Window actions
The form views
Dealing with several views of the same type
Business document views
The header
The document sheet
Title and subtitle
Smart buttons area
Grouping content in a form
Tabbed notebooks
View semantic components
Fields
Labels for fields
Relational fields
Field widgets
Buttons
Smart buttons
Dynamic views
On change events
Dynamic attributes
List views
Search views
Calendar views
Graph and pivot views
Other view types
Summary
Kanban Views and Client-Side QWeb
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 templating 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 dicts and lists
Inheritance on Kanban views
Custom CSS and JavaScript assets
Summary
Reports and Server-Side QWeb
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
Creating Website Frontend Features
Roadmap
Our first web page
Hello World!
Hello World! with a QWeb template
Extending web features
HelloCMS!
Building websites
Adding CSS and JavaScript assets
The to-do list controller
The to-do list template
The To-Do Task detail page
Website forms
The form page
Accessing the security and menu item
Adding custom logic
Summary
Debugging and Automated Tests
Unit tests
Adding unit tests
Setting up tests
Writing test cases
Testing exceptions
Running tests
About YAML tests
Development tools
Server development options
Debugging
The Python debugger  
A sample debugging session
Alternative Python debuggers
Printing messages and logging 
Killing running processes
Summary
Deploying and Maintaining Production Instances
Available prebuilt packages
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/sysvinit service
Checking the Odoo service from the command line
Using a reverse proxy
Setting up Nginx as a reverse proxy
Enforcing HTTPS
Nginx optimizations
Long polling
Server and module updates
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Odoo is a full featured open source platform to build 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. Extensions and modifications can be implemented as modules, to be applied over the module with the feature being changed, without actually changing it. This provides a clean and easy -to-control and customized applications.
This capability to combine several modules into feature-rich applications, along with the open source nature of Odoo, are probably important factors explaining the community that grew 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 11 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 nearby every time you are working with Odoo.
This book was written keeping in mind developers with minimal programming knowledge but a strong will to learn. We will use a lot the Python language and explain how to run Odoo in a Ubuntu/Debian system, but little previous knowledge on them is assumed. The code examples are kept simple and clear, and they are accompanied with appropriate explanations to help build up the knowledge on them.
Experienced developers, already familiar with Odoo, should also be able to benefit from this book. Not only does it allow them to consolidate their knowledge, it also provides an easy way to get up to date with all the details that changed with Odoo 11.0. In fact, special care was taken to highlight all the relevant changes between 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 porting modules to other versions.
This books contains 14 chapters, which can be seen to be organized in five parts, roughly, 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 with thorough, step-by-step creation of a new Odoo module:
Chapter 1, Quick Start – The Odoo Developer Mode and Concepts, visually introduces the Odoo development concepts, creating a simple Odoo application directly from the user interface. An existing Odoo installation, or an Odoo.com instance, can be used, so no local setup is needed.
Chapter 2, Installing and Organizing the Development Environment, explains how to install Odoo from source and how to set up the development environment to be used throughout the book. We choose to install Odoo in an Ubuntu host, but guidance is given to have a perfectly functioning development environment in a Windows machine with an Ubuntu virtual machine.
Chapter 3, Your First Odoo Application – A Practical Overview, provides a step-by-step guide through the creation of our first Odoo module. While the example is kept 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.
The second part of the book introduces Models, responsible for the data model structures around which the application is built:
Chapter 4, 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.
Chapter 5, Import, Export, and Module Data, covers the most used Odoo data file formats—XML and CSV—the external identifier concept, how use to data file in modules, and data import/export operations.
In the third part, we explain how to write the business logic layer on top of the Models—the "Controller "component of the architecture:
Chapter 6, The ORM API – Handling Application Data, goes further into the ORM, explaining how it can be used to manipulate the data in the Models. The API for social features, such as followers and notifications, is also explained.
Chapter 7, Business Logic – Supporting Business Processes, explains how to program business logic on the server side, leveraging the ORM concepts and features. It also explains how to use wizards for a more sophisticated user interaction.
Chapter 8, External API – Integrating with Other Systems, shows how to implement Odoo external 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 that layer:
Chapter 9, 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 10, 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 11, Reports and Server-Side QWeb, discusses using the QWeb-based report engine and everything needed to generate printer-friendly PDF reports.
Chapter 12, 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 for development environments, need to be taken into account when deploying for production use.
Chapter 13, Debugging and Automated Tests, shares some debugging techniques to be used when developing Odoo modules. How to implement automated tests is also explained, since this is an essential practice to produce reliable code.
Chapter 14, Deploying and Maintaining Production Instances, shows us how to prepare a server for production prime time, explaining what configuration should be taken care of and how to configure an Nginx reverse proxy for improved security and scalability.
At 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 production deployment and maintenance of these applications.
Other than being familiar with programming, no particular knowledge is expected to be able to take advantage of this book.
Odoo is built using the Python programming language, so it is a good idea to get solid 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 find complementary readings on the Python programming language, 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 with the help of VirtualBox. Of course, working from an Ubuntu/Debian system is also a possible choice.
All the required software is freely available, and the instructions on where to find it will be given.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.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.packtpub.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-11-Development-Essentials-Third-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
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: "We will have a new /todo_app directory alongside the /odoo directory containing the modules."
A block of code is set as follows:
<?xml version="1.0"?> <odoo> <!-- Content will go here... --> </odoo>
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
'data': [ 'security/ir.model.access.csv',
'views/todo_menu.xml', 'views/todo_view.xml',
]
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 onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In the web client, access the Apps top menu and select the Update Apps List menu option."
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.packtpub.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.packtpub.com.
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 packtpub.com.
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 and Calendar 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 app. 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. Once we have built our app, it needs to be tested, deployed to a production environment, and maintained. The final part of the book will cover these topics.
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.
We will learn about the Odoo architecture, to understand where each of the components fit. Then we will use the Developer mode to create a simple Library app, learning how to add fields to existing Models, add new Models, create our custom Views for them, and make them available to users through Menu Items.
We will next provide a high-level overview of the Odoo architecture, before we perform a hands-on customization using the Developer mode.
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 RDBMS, 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 a filesystem.
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 addon 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 is the included website framework. It gives full flexibility to create web pages as 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 intrinsic logic. Frontend developers will probably feel very much at home in this space.
Due to the openness of the Odoo server API, other client implementations are possible, and could be built in almost any platform or programming language. Desktop and smartphone apps can be built to provide specific user interfaces, leveraging the Odoo Data and Logic tiers for business logic and data persistence.
A particular example of a third-party Odoo client is ERPpeek. It is a command- line client, allowing you to connect and interact with remote Odoo servers. It can be useful for developers or system administrators with Odoo technical knowledge, to inspect data on the server, script advanced operations, or perform maintenance operations. We will present an overview of ERPpeek in Chapter 8, External API – Integrating with Other Systems.
Many Odoo customizations can be made directly from the user interface.
This has the advantage of being a rather quick way to make changes to applications. It can be used from small modifications, such as adding a field, to larger customizations, such as creating an app with several models, views, and menu items.
These customizations done directly from the user interface have some limitations, when compared to customizations done with programming tools, covered throughout the rest of this book. For example, you can't add or extend ORM methods (although Automated Actions can be used as a close alternative to that). They also can't be easily integrated into a structured development workflow, such as running automated tests and deploying into several environments (for example, quality assurance, pre-production, and production).
Odoo 10.0 introduced Odoo Studio, an app designer to create customizations from the user interface. We won't discuss Odoo Studio here, but it ends up being a user-friendly frontend for the developer tools we introduce throughout this chapter, so the limitations on customizations possible are about the same. Odoo Studio does include an important additional feature, that is, the ability to export the customizations done in a convenient module package. It can be very helpful to allow power users to create customizations in a SaaS instance or simpler self-hosted technical environments.
The remainder of this book explains how to develop for Odoo in a structured way, creating addon modules with your code editor.
But in this chapter, we will be using the Developer mode features to perform customizations directly from the web client user interface, since it is important for an Odoo developer to have a good understanding of these tools and what can be achieved with them.
But more importantly, the goal for this exercise is to gain a good understanding of the several layers involved in an Odoo application, and how their components are organized.
Enough talk; let's get busy trying out these tools.
To explain the developer tools, we will use a simple project: we will create a very simple Library app. Our Library aims to keep a record of our Books and their Authors. It should keep a list of the Authors and the Books authored by each Author.
Our Library app needs two Models: Authors and Books. These two Models have a many-to-many relationship between them: each Author can have many Books, and each Book can have many Authors.
Odoo already provides the built-in Partner Model, with the res.partner technical name, to represent people, organizations, and addresses. For example, customers, suppliers, contact people, and application users are all Partners.
We will make our life simpler if we reuse it for the Authors of our Library app. We will be adding an Is Book Author? flag to this Model, and a menu item showing only the Author Partners.
The book we will create has a completely new Model, the corresponding form, and list views, and a menu item to access them.
We will be needing an Odoo test database to work with.
In Chapter 2, Installing and Organizing the Development Environment, we will explain how to install Odoo from source and set up our development environment. But we want to skip that for now, and start working directly from the user interface of some existing Odoo server.
If by chance you have a self-hosted Odoo installation working, that's perfect; we can use it to go through the rest of this chapter. At the login screen, access the Manage Databases menu option and create a new database to play with.
If you don't have an Odoo installation available, you can instead create a test database at Odoo.com to follow this chapter. The user interface there will be from the Odoo Enterprise Edition, so it will be a little different from the screenshots you will find here, but that should not be a problem. To create a new database, you will probably be asked to select a starting app. No specific app is required to follow this chapter, but if you're unsure on what to pick, CRM would be fine.
Now, access the Odoo database with your browser and log in. For Odoo online, the address should be something like https://<mydbname>.odoo.com. For a self-hosted instance, it should be something like http://<server-address>:8069. The 8069 port is the Odoo default. If your installation uses a different port, you should change it accordingly.
We will be using the Contacts Directory app, so the first thing to do is to install it. Open the Apps top menu, look up this app, and install it, if you have not already done so:
Now that we have an Odoo instance to work with, the next step is to enable the developer tools, that give us the access to the Odoo internals.
In Settings | Dashboard, at the bottom right, you can find the Activate the developer mode link. Clicking on it enables the Developer mode features for this browser window.
We also have available an Activate the developer mode (with assets) option. What it does is to 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.
Once the Developer mode is enabled, we will see two additional menus available:
The Debug menu, the bug icon at the right-hand side of the top menu bar, just before the username and avatar
The
Technical
menu item, in the
Settings
app:
We will be explaining and making use of these Developer mode features in the next sections of this chapter.
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 Library app, we want to add the Is Book Author? flag to the Partner model, to make it easier to list everyone who is a book author.
To do this, in the Settings app, go to the Technical | Database Structure | Models menu item, and look up the res.partner model, with Contacts for Model Description. Click on it to open the corresponding 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 Add an item at the bottom of the Fields list. A pop-up window will be presented for the new field creation.
Let's fill in the configuration:
Field Name:
x_is_book_author
Field Label:
Is Book Author?
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 addon modules don't have this limitation.
That's it. Click Save & 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 at the top left of the Fields list.
Now, click on the top-left Save button to make this change permanent.
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 Views.
Still, on the Partner/Contact Model form, click on the Views tab, and we will be able to see all the View definitions for the res.partner model. As you can see, each View is a record in the database. Changing or adding View records is immediately effective, and will be visible the next time that View is reloaded.
There are a couple of important things to notice in the Views list.
We can see that there are several View Type, such as Form, Tree, Search, or Kanban. The Search views are actually definitions on the filters available in the top-right search box. The other view types are the different ways the data can be displayed. The basic ones are Tree, for list views, and Form, for the detailed form view.
If you sort the list by View Type, you will notice that the same view type can have multiple definitions. In fact, we can have several Base view definitions, the ones with an empty Inherited View field. And we can have several Extension view definitions, also called Inherited Views, adding incremental changes to a base view, for example, to add a field to an existing form.
For the res.partner model, we can see that there are two base forms: res.partner.form and res.partner.simplified.form. Client Actions, such as the ones in menu items, can specify the particular base view to use. If none are defined, the one with the lowest Sequence is used. You can think of it as being the default view. Clicking on a Views line, we will see a form with the View's details, including the Sequence value.
To learn what the specific view used somewhere in the user interface is, we can inspect it using the Debug menu. Let's try it now. Click on the Contacts app and we will be presented with a list of contact cards. Clicking on any of the cards will show us the corresponding FormView. Now, on the Debug menu (the bug icon at the top right), select the Edit FormView option:
This will show the same view details form we saw before in Models, but positioned on the actual view definition used here. As you can see, it is the res.partner.form view.
In the Architecture field, we can see the XML with the view definition. We could just edit it to add our new field. While that works, in the long run it is not a good idea. This view is owned by an addon module, and if some time in the future that module is upgraded, these customizations would be overwritten and lost. We can learn about the owner module through the External ID field. In this case, it is base.view_partner_form, so we know that this view belongs to the base module.
The proper way to modify a view is to create an Inherited View extension.
First, we need to pick an element from the original view to use as the extension point. We can do that by inspecting the base view and choosing an XML element with a name attribute. Most of the time, this will be a <field> element. Here, we will pick the <field name="category_id" ...> element.
Now, open the Debug menu, click on the Edit Form View option, select the Inherited Views tab, and click on Add an item at the bottom of the list.
A pop-up window, Create: Views which inherit from this one, will be shown, and we should fill it with the following values:
View Name
:
Contacts - Custom Is Book Author Flag
Architecture
: Use the following XML:
<field name="category_id" position="after"> <field name="x_is_book_author" /></field>
The other important fields, such as the Model, View Type, and Inherited View, already have correct default values.
We can now Save & Close. Save in the Edit Form View window and then close it. We will be able to see the change done once we reload the Contacts form view. This means reloading the page in your web browser. In most browsers, you would do that by pressing F5.
Now we will be creating new application features, rather than extending already existing ones. We will continue working on our Library project.
First, we want to add a Library top menu, and we can already add the Books Authors menu item to it. Next, we will create a new Model for Books, and make it available to users by adding a menu item for it. Finally, we will create the list and form views for the Books model.
We now have a way to list Authors. It is the list of all Partners with the Is Book Author? flag checked.
Now, we want to add an Authors menu item that opens that list, filtering away the other Partners that are not Authors. The good news is that we can do this pretty easily by reusing the already existing Partner views.
Before that, we want to create the top menu item for our shiny new Library app, under which we will be including the menu item for the Authors, and later a menu item for Books.
The menu definitions can be seen in the Settings app, at Technical | User Interface | Menu Items. Create a new menu item using the following values:
Menu:
Library
Parent Menu: (empty)
Action: (empty)
In the Submenus tab, click on Add an item to add a sub-menu using these values:
Menu:
Book Authors
Parent Menu:
Library
(the default value)
Action: Select
ir.actions.act_window
, and in the selection list on the right click on
Create and Edit
, opening a form to create the related Window Action. Set the following values on the Window Action:
Action name:
Book Authors
Object:
res.partner
(the technical name of the target Model):
Save all the forms we opened, and the menu tree for our Library app should be ready to use:
To see changes in the menu, we need to reload the web client. We can see that the menu is a tree of menu items, with parent/child relations. The leaf menu items have a related Action, defining what happens when it is selected. This Action name is what will be used as the title of the presented views.
There are several Actions types available, and the most important ones are Window, Reports, and Server Actions. Window Actions are the most frequent ones, and are used to present Views in the web client. Report Actions are used to run reports and Server Actions are used to define automated tasks.
At this point, we are concerned with Window Actions that are used to display views.
The Menu Item we just created for Book Authors uses a Window Action, which was created directly from the Menu Item form. We can also view and edit it from the Settings | Technical | Actions menu options. In this particular case, we are interested in the Window Actions menu option.
It happens that the Book Authors Action we created is too simple, and does not perform what we want: it opens a list with all Partners, regardless of whether they have the Is Book Author? set. We need to fix that.
Open the Window Actions menu item, look up our recently created Book Authors action, and edit it. We are interested in the Filters section, found inside the General Settings tab.
The Domain Value field can have an expression defining a filter for the records to be presented. This "domain expression" follows an Odoo-specific syntax that will be explained in later chapters. For now, it's enough to know that it is a list of triplets, where each triplet is a filter condition.
In our case, the expression to use for the Domain Value is:
[('x_is_book_author', '=', True)]
For usability, we would also want new records created to have the Is Book Author? flag checked by default. An Action is able to do this, allowing us to set default values on the views it presents. This is done using the Context Value. The Context is the way Odoo passes around session information, including default values to be used. It will be discussed in detail in later chapters, and for now we just need to know that it is a dictionary of key-value pairs. Values prefixed with default_ provide the default value for the corresponding field.
In our case, the expression needed for the Context Value is:
{'default_x_is_book_author': True}
That's it. If we now try the Library | Book Authors menu option, it should list only Partners with the Is Book Author? flag checked, if any. And if we try to create a new Book Author, we will see that the Is Book Author? checkbox will be conveniently checked by default.
We now have a Library top menu with a menu item for Book Authors. It's time to add a Books menu item to hold the records for books.
Let's visit again, in Settings, the Technical | Database Structure | Models menu, and click on Create. Fill in the Model form with these values:
Model Description:
Book
Model:
x_library_book
We should save it before we can properly add new fields to it. So click on Save and then Edit
