Odoo Development Cookbook - Consultor Odoo ERP

Transcription

Odoo DevelopmentCookbookBuild effective applications by applying Odoo developmentbest practicesHolger BrunnAlexandre FayolleDaniel ReisBIRMINGHAM - MUMBAI

Odoo Development CookbookCopyright 2016 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, ortransmitted 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 theinformation presented. However, the information contained in this book is sold withoutwarranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealersand distributors will be held liable for any damages caused or alleged to be caused directly orindirectly by this book.Packt Publishing has endeavored to provide trademark information about all of the companiesand products mentioned in this book by the appropriate use of capitals. However, PacktPublishing cannot guarantee the accuracy of this information.First published: April 2016Production reference: 1260416Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirmingham B3 2PB, UK.ISBN 978-1-78588-364-4www.packtpub.comFM-2

CreditsAuthorsHolger BrunnProject CoordinatorKinjal BariAlexandre FayolleDaniel ReisReviewersGuewen BaconnierStefan RijnhartAcquisition EditorManish NainaniContent Development EditorMehvash FatimaProofreaderSafis EditingIndexerMonica Ajmera MehtaProduction CoordinatorArvindkumar GuptaCover WorkArvindkumar GuptaTechnical EditorsMenza MathewDeepti TuscanoCopy EditorsMerilyn PereiraAlpha SinghFM-3

About the AuthorsHolger Brunn has been a fervent open source advocate since he came in to contactwith the open source market sometime in the nineties. With an academic background inphilosophy and sociology, he turned his interest to generalized logic, which proves helpful inmany aspects of his IT work. Turning into a professional programmer was a side effect of hishobbyist interest, combined with a part-time job with a very open-minded mentor to whom heowes a lot of gratitude.He has programmed for ERP and similar systems in different positions since 2001. For thelast eight years, he has dedicated his time to TinyERP, which became OpenERP and evolvedinto Odoo. Currently, he works at Therp BV in the Netherlands as a developer and is an activemember of the Odoo Community Association (OCA). He's most interested in fundamental workon technical modules, but also enjoys contributing to other projects, with a focus on UI andwebsite widgets, CRM, and knowledge management.Alexandre Fayolle started working with Linux and free software in the mid 1990s andquickly became interested in the Python programming language. Between 1999 and 2012, hehelped manage Logilab, a company he cofounded, he specialized in Python development, andhad the opportunity to work on projects for large companies such as EDF, Arcelor-Mittal, andGdF Suez (now Engie) using the Cubicweb framework.He also tackled fun projects involving machine learning, natural language processing, andmulti-agent systems. In 2012, he joined Camptocamp to share his expertise on Python,PostgreSQL, and Linux with the team implementing Odoo (OpenERP at the time). Hecurrently manages projects for Camptocamp and is strongly involved in the Odoo CommunityAssociation. In his spare time, he likes to play the vibraphone in a jazz quartet, but hasrecently been known for writing a book about Odoo, which he hopes you'll enjoy.FM-4

Daniel Reis has been working in the IT industry for over 15 years in developer, consultant,and management roles. Most of this work was at the Capgemini multinational consultancyfirm, implementing proprietary business solutions for reference companies in a variety ofsectors, such as industry, telecommunications, and banking. Daniel has a BSc in appliedmathematics and a master's in business administration from the ISCTE Business School.He's worked with Odoo solutions (formerly OpenERP) since 2010, and he is an activecontributor in the Odoo community association projects. He has been a speaker at the OpenDays annual conference and other open source events. He is the author of the first Odoodevelopment book: Odoo Development Essentials, also by Packt Publishing.He currently works at Securitas, the global security services company, where he hasintroduced Python, Odoo, and other open source solutions into the company's ITapplications portfolio.I thank my wife, Maria José, for all the support and patience that made thisbook possible.FM-5

About the ReviewersGuewen Baconnier is a discrete guy who does not enjoy being put forward. He worksat Camptocamp where he's been a TinyERP programmer before moving to OpenERP andnow Odoo. He is a free software enthusiast and an active member of the Odoo CommunityAssociation (OCA), where his responsibilities involve, among others, being the lead developerof the OCA Connector Framework. Guewen also loves books so should you come across him,there is a good chance he may have his nose in one, either reading a technical book to keep upwith his boundless curiosity and hunger to learn, or reading a novel to journey in some fictionaluniverse, or whatever good read fell into his hands. He likes to hike in the countryside with hisbeloved wife. He is also the happy father of two nice kids, with whom he enjoys spending time,strolling, going to the library, reading books, and playing Kerbal Space Program.I would like to thank my wife and kids for supporting my tiredness on themorrows of long evenings of reviewing. And I would like to thank AlexandreFayolle who helped me shape this short biography. Finally, thanks to mycolleagues and to all contributors of the OCA from whom I learn every day.Stefan Rijnhart is a life-long open source advocate and has been a full time Odooconsultant and developer since 2010. He enjoys collaborating in the Odoo CommunityAssociation (OCA), which he finds to be mutually beneficial to his customers' projects. In theOCA, Stefan played a key role in the creation of the OpenUpgrade migration project for Odooand in the Odoo Community Backports project (OCB). Offline, you can find him riding a carrierbicycle through the streets of Amsterdam with his son on the front seat, or playing music withhis band. Get in touch with Stefan at http://opener.amsterdam.FM-6

www.PacktPub.comeBooks, discount offers, and moreDid you know that Packt offers eBook versions of every book published, with PDF and ePubfiles available? You can upgrade to the eBook version at www.PacktPub.com and as a printbook customer, you are entitled to a discount on the eBook copy. Get in touch with us atcustomercare@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, sign upfor a range of free newsletters and receive exclusive discounts and offers on Packt booksand ion/packtlibDo you need instant solutions to your IT questions? PacktLib is Packt's online digital booklibrary. Here, you can search, access, and read Packt's entire library of books.Why subscribe?ffFully searchable across every book published by PacktffCopy and paste, print, and bookmark contentffOn demand and accessible via a web browserFM-7

Table of ContentsPrefaceChapter 1: Installing the Odoo Development Environmentvii1IntroductionEasy installation of Odoo from sourceManaging Odoo environments using the start commandManaging Odoo server databasesStoring the instance configuration in a fileActivating the Odoo developer toolsUpdating Odoo from source12910192225Chapter 2: Managing Odoo Server Instances29Chapter 3: Creating Odoo Modules47IntroductionConfiguring the addons pathUpdating the addon modules listStandardizing your instance directory layoutInstalling and upgrading local addon modulesInstalling addon modules from GitHubApplying changes to addonsApplying and trying proposed pull requests2930313336404243IntroductionCreating and installing a new addon moduleCompleting the addon module manifestOrganizing the addon module file structureAdding modelsAdding Menu Items and ViewsUsing scaffold to create a module47484952555761i

Table of ContentsChapter 4: Application Models63Chapter 5: Basic Server Side Development95IntroductionDefining the Model representation and orderAdding data fields to a modelUsing a float field with configurable precisionAdding a monetary field to a ModelAdding relational fields to a ModelAdding a hierarchy to a ModelAdding constraint validations to a ModelAdding computed fields to a ModelExposing Related fields stored in other modelsAdding dynamic relations using Reference fieldsAdding features to a Model using inheritanceUsing Abstract Models for reusable Model featuresUsing Delegation inheritance to copy features to another ModelIntroductionDefining model methods and use the API decoratorsReporting errors to the userObtaining an empty recordset for a different modelCreating new recordsUpdating values of recordset recordsSearching for recordsCombining recordsetsFiltering recordsetsTraversing recordset relationsExtending the business logic defined in a ModelExtending write() and create()Customizing how records are searchedChapter 6: Advanced Server Side Development TechniquesIntroductionChange the user performing an actionCall a method with a modified contextExecute raw SQL queriesWrite a wizard to guide the userDefine onchange methodsCall onchange methods on the server sidePort old API code to the new 7109110112114117120125125126128130133138141143

Table of ContentsChapter 7: Debugging and Automated Testing153Chapter 8: Backend Views179Chapter 9: Module Data219Chapter 10: Access Security233IntroductionProducing server logs to help debug methodsUsing the Odoo shell to interactively call methodsUsing the Python debugger to trace method executionWriting tests for your module using YAMLWriting tests for your module using Python unit testsRunning server testsUsing the Odoo Community Association maintainer quality toolsIntroductionAdding a menu item and window actionHaving an action open a specific viewAdding content and widgets to a form viewAdding buttons to formsPassing parameters to forms and actions: ContextDefining filters on record lists: DomainList viewsSearch viewsChanging existing views: View inheritanceDocument-style formsDynamic form elements using attrsEmbedded viewsKanban viewsShow kanban cards in columns according to their stateCalendar viewsGraph and pivot viewsQWeb reportsIntroductionUsing external IDs and namespacesLoading data using XML filesUsing the noupdate and forcecreate flagsLoading data using CSV filesLoading data using YAML filesAddon updates and data migrationCreate security groups and assign them to usersAdd security access to 28229233238iii

Table of ContentsLimit access to fields in modelsLimit record access using record rulesUsing security group to activate features241243246Chapter 11: Internationalization253Chapter 12: Automation and Workflows269Chapter 13: Web Server Development295Chapter 14: CMS Website Development311Chapter 15: Web Client Development325Installing a language and configure user preferencesConfigure language-related settingsTranslate texts through the web client user interfaceExporting translation strings to a fileUse gettext tools to ease translationsImport translation filesIntroductionUsing Kanban stages and featuresCreating server actionsAdding messaging and tracking featuresUsing Python code server actionsUsing automated actions on time conditionsUsing automated actions on event conditionsInspecting built-in workflowsIntroductionMake a path accessible from the networkRestrict access to web accessible pathsConsume parameters passed to your handlersModify an existing handlerUsing the RPC APIIntroductionExtending CSS and JavaScript for the websiteCreating or modifying templates - QWebOffering snippets to the userIntroductionCreating custom widgetsUsing client-side QWeb templatesMaking RPC calls to the serverWriting tests for client side codeDebugging your client side 5295300302304307311311314318325325331333336340

Table of ContentsChapter 16: Server Deployment345Index371IntroductionInstalling Odoo for productionAdapting the configuration file for productionSet up Odoo as a system serviceConfigure a reverse proxy and SSLUse buildout for repeatable builds345345351355357362v

PrefaceOdoo, formerly known as OpenERP, is a great platform for developers. The framework atits core is very rich and allows building client–server applications from scratch as well asadapting existing applications to your needs through a clever extension mechanism and avery modular design. The latest versions have brought a wealth of new possibilities with theaddition of a full-featured website development stack. The scope is huge and it is easy fornewcomers to feel lost.For years, Odoo developers have been learning their craft by reading the code of the addonmodules, which are built on top of the framework to provide enterprise management features.While effective, the process is long and error prone, since it is difficult to know whether thesource code you are learning from is using the latest possibilities offered by the framework,or if you are looking at an older module that has not been updated to use these features. Tomake things worse, some code flows are intrinsically hard to follow because they're partly inthe business logic layer, partly in the database layer, partly in the request handling layer, andpartly in the client side code. The introduction of a new API in version 8 has made things evenmore confusing, since most of the code base was not immediately ported to this new API.This book is meant to save you time by tapping in to the years of experience accumulatedby long-time Odoo contributors to learn the current best practices in Odoo development byfocusing on the new features of version 9, and also giving a solid base in the existing maturefunctionality of the framework. Since Odoo has a long tradition of guaranteeing backwardcompatibility, most of the presented material should still work with the upcoming versions.What this book coversThis book contains 16 chapters. We tried hard to make each chapter as independent aspossible, and to make the various recipes in each chapter self-contained.Chapter 1, Installing the Odoo Development Environment, explains how to create adevelopment environment for Odoo, start Odoo, create a configuration file, and activatethe developer tools of Odoo.vii

PrefaceChapter 2, Managing Odoo Server Instances, is about addon installation and upgrading.It provides useful tips for working with addons installed from GitHub, and organizing thesource code of your instance.Chapter 3, Creating Odoo Modules, explains the structure of an Odoo addon module andgives a step-by-step guide for creating a simple module from scratch.Chapter 4, Application Models, focuses on Odoo model descriptions, and explains the variousfield types and the different inheritance models available in Odoo.Chapter 5, Basic Server Side Development, introduces the v8 API of Odoo, presents thecommonly used methods of the Model class, and explains how to write business logic methods.Chapter 6, Advanced Server Side Development Techniques, deals with more advanced topicsuseful when writing business methods such as writing wizards to walk the user through aprocess or writing onchange methods. It also covers porting code from the old API to thev8 API.Chapter 7, Debugging and Automated Testing, proposes some strategies for server-sidedebugging and an introduction to the Python debugger. It also explains how to write andrun automated tests using YAML or Python for your addon modules.Chapter 8, Backend Views, explains how to write business views for your data models and howto call server-side methods from these views. It covers the usual views (list view, form view,and search view) as well as the views introduced in recent versions of Odoo (Kanban, graph,calendar, pivot, and so on)Chapter 9, Module Data, shows how to ship data along with the code of your module. It alsoexplains how to write a migration script when a data model provided by an addon is modifiedin a new release.Chapter 10, Access Security, explains how to control who has access to what in your Odooinstance, by creating security groups, writing access control lists to define what operations areavailable to each group on a given model, and, if necessary, by writing record level rules.Chapter 11, Internationalization, deals with the translation of the user interfaces of your addons.Chapter 12, Automation and Workflows, illustrates the different tools available in Odoo toimplement business process for your records. It also shows how server actions and automatedrules can be used to support business rules.Chapter 13, Web Server Development, deals with the core of the web server in Odoo. Itexplains how to map URLs to methods and how to control who can access these URLs.Chapter 14, CMS Website Development, shows how to customize websites built with Odoo, bywriting your own templates and providing new snippets for use in the website builder.viii

PrefaceChapter 15, Web Client Development, dives into the JavaScript part of Odoo and explainshow you can provide new widgets and make RPC calls to the server. It also gives tips aboutdebugging and testing this part of your code.Chapter 16, Server Deployment, provides advice on how to install and configure Odoo forproduction, including setting up a reverse proxy to encrypt network communications overHTTPS and ensuring that Odoo starts when the server boots.Who this book is forThis book is targeted at Python developers who want to learn Odoo development orconsolidate their Odoo skills. Some experience with the JavaScript programming languageand web development in general is required to fully benefit from the frontend chapters.This book focuses on core application development. It does not cover how to use the businessapplications provided by Odoo. You may want to refer to Working with Odoo, by Greg Moss,for this.This book does not provide explanations about how the internals of the enterprisemanagement applications work. To understand this, you will have to read the source code andexperiment for yourself. Being familiar with the contents of the Odoo Development Cookbookshould make your life easier, as it contains pointers to parts of the code you can read to learnabout a specific topic.What you need for this bookThe set up recipes in Chapter 1, Installing the Odoo Development Environment, and Chapter 15,Web Client Development, expect that you are working on a server running Debian GNU/Linux, ora derivative distribution such as Ubuntu, in a reasonably up-to-date release. If you are runninganother distribution, things should be fairly straightforward; the main differences should bein the names of the packages to install, and possibly the location of the configuration files ofPostgreSQL and Nginx.If your workstation is running Windows or MacOS, we advise you to set up a Debian virtualmachine to work with Odoo. While it is possible to develop natively on Windows or Mac, havinga development environment as close as possible to the deployment environment is a good wayto avoid nasty surprises and GNU/Linux is the recommended deployment platform for Odoo.ix

PrefaceIs there a recommended Integrated Development Environment (IDE) for Odoo? This is afrequently asked question by newcomers. The best answer is to use whatever tool youare familiar with. Popular choices include Eclipse or PyCharm, but a very high number ofexperimented developers, including th

strolling, going to the library, reading books, and playing Kerbal Space Program. I would like to thank my wife and kids for supporting my tiredness on the morrows of long evenings of reviewing. And I would like to thank Alexandre Fayolle who he