SlideShare ist ein Scribd-Unternehmen logo
1 von 137
Odoo
(Build module, Security, ORM)
Build an Odoo module
Outlines:
• Modularity
• Module structure in odoo
• Manifest file
• Xml with odoo
Modularity
• Modular programming is a software design
technique to split your code into separate
parts. These parts are called modules. The
focus for this separation should be to have
modules with no or just few dependencies
upon other modules.
• The executable application will be created by
putting the modules together.
• Advantages:
• Readable
• reliable
• reusable
• easier to debug and manage
Do not reinvent the wheel !!
• Before beginning a new module
development, find out if there is any
module that might solve your problem
totally or partially.
• If you decide to develop a new module,
analyze what features you will need in
other modules, and try to encapsulate them
in other module so that you can inherit
them later
Module structure in odoo
Directories:
• A module is organized in important
directories that contain the business logic.
• Module directories are specified by using the
–-addons-path.py option.
• An Odoo module is declared by its manifest.
• The manifest file serves to declare a python
package as an Odoo module and to specify
module metadata.
• A module is also a Python package with a
__init__.py file, containing import
instructions for various Python files in
the module.
Directories
• data/ : demo and data xml
• models/ : models definition
• controllers/ : contains controllers (HTTP
routes).
• views/ : contains the views and templates
• static/ : contains the web assets, separated
into css/, js/, img/, lib/, ...
Other optional directories compose the
module:
wizard/ : regroups the transient models
(formerly osv_memory) and their views.
report/ : contains the reports (RML report
[deprecated], models based on SQL views (for
reporting) and other complex reports). Python
objects and XML views are included in this
directory.
tests/ : contains the Python/YML tests
Security/
i18n/: used for translating
Odoo follows an MVC-like architecture:
• The model layer, defining the structure of the
app's data.
• The view layer, describing the user interface
• The controller layer, supporting the business
logic of the application
Odoo provides a mechanism to help set up a new
module, odoo-bin has a subcommand scaffold
to create an empty module:
odoo-bin scaffold <module name> <where to
put it>
Starting with odoo
Configuring the addons path:
• The Odoo server has a configuration option called
addons_path to set where the server should look
for modules. By default, this points to the /addons
directory, where the Odoo server is running.
• We can provide not only one, but a list of
directories where modules can be found. This allows
us to keep our custom modules in a different
directory, without having them mixed with the
official addons.
$ ./odoo-bin -d demo –addons path="../custom_addons_app,./addons"
Manifest content
• name (str, required)the human-readable name
of the module .
• version (str)this module's version, should
follow semantic versioning rules .
• description (str)extended description for the
module.
• author (str)name of the module author.
• website (str)website URL for the module
author.
• license (str, defaults: LGPL-3)distribution
license for the module
category (str, default: Uncategorized)
classification category within Odoo, rough
business domain for the module.
Although using existing categories is
recommended, the field is freeform and
unknown categories are created on-the-fly.
data (list(str))List of data files which must
always be installed or updated with the
module. A list of paths from the module root
directory.
demo (list(str))List of data files which are only
installed or updated in demonstration mode.
installable (bool default: False)Whether a user
should be able to install the module from the
Web UI or not.
auto_install (bool, default: False)If True, this
module will automatically be installed if all of its
dependencies are installed.
external_dependencies (dict(key=list(str)))A
dictionary containing python and/or binary
dependencies.
depends (list(str))Odoo modules which must
be loaded before this one, either because this
module uses features they create or because
it alters resources they define . When a
module is installed, all of its dependencies are
installed before it. Likewise dependencies are
loaded before a module is loaded.
application (bool, default: False)Whether the
module should be considered as a fully-
fledged application (True) or is just a
technical module (False) that provides some
extra functionality to an existing application
module.
css (list(str))Specify css files with custom
rules to be imported, these files should be
located in static/src/css inside the module.
images (list(str))Specify image files to be used
by the module.
maintainer (str)Person or entity in charge of
the maintenance of this module, by default it is
assumed that the author is the maintainer.
{pre_init, post_init, uninstall}_hook (str)Hooks
for module installation/uninstallation, their value
should be a string representing the name of a
function defined inside the module's __init__.py.
pre_init_hook takes a cursor as its only
argument, this function is executed prior to the
module's installation.
post_init_hook takes a cursor and a registry as
its arguments, this function is executed right
after the module's installation.
uninstall_hook takes a cursor and a registry as
its arguments, this function is executed after
the module's uninstallation.
These hooks should only be used when
setup/cleanup required for this module is either
extremely difficult or impossible through the
api.
File naming
• For views declarations, split backend views
from (frontend) templates in 2 different
files.
• For models, split the business logic by sets of
models, in each set select a main model, this
model gives its name to the set. If there is
only one model, its name is the same as the
module name.
For each set named <main_model> the following
files may be created:
• models/<main_model>.py
• models/<inherited_main_model>.py
• views/<main_model>_templates.xml
• views/<main_model>_views.xml
• For data, split them by purpose : demo or
data. The filename will be the main_model
name, suffixed by _demo.xml or _data.xml.
• For controllers, the only file should be named
main.py. Otherwise, if you need to inherit an
existing controller from another module, its
name will be <module_name>.py. Unlike models,
each controller class should be contained in a
separated file.
• For static files, since the resources can be
used in different contexts (frontend,
backend, both), they will be included in only
one bundle. So, CSS/Less, JavaScript and
XML files should be suffixed with the name
of the bundle type.
• Don't link data (image, libraries) outside
Odoo: do not use an URL to an image but copy
it in our codebase instead.
• addons/<my_module_name>/
• |-- __init__.py
• |-- __manifest__.py
• |-- controllers/
• | |-- __init__.py
• | |-- <inherited_module_name>.py
• | `-- main.py
• |-- data/
• | |-- <main_model>_data.xml
• | `-- <inherited_main_model>_demo.xml
• |-- models/
• | |-- __init__.py
• | |-- <main_model>.py
• | `-- <inherited_main_model>.py
• |-- report/
• | |-- __init__.py
• | |-- <main_stat_report_model>.py
• | |-- <main_stat_report_model>_views.xml
• | |-- <main_print_report>_reports.xml
• | `-- <main_print_report>_templates.xml
• |-- security/
• | |-- ir.model.access.csv
• | `-- <main_model>_security.xml
• |-- static/
• | |-- img/
• | | |-- my_little_kitten.png
• | | `-- troll.jpg
• | |-- lib/
• | | `-- external_lib/
• | `-- src/
• | |-- js/
• | | `-- <my_module_name>.js
• | |-- css/
• | | `-- <my_module_name>.css
• | |-- less/
• | | `-- <my_module_name>.less
• | `-- xml/
• | `-- <my_module_name>.xml
• |-- views/
• | |-- <main_model>_templates.xml
• | |-- <main_model>_views.xml
• | |-- <inherited_main_model>_templates.xml
• | `-- <inherited_main_model>_views.xml
• `-- wizard/
• |-- <main_transient_A>.py
• |-- <main_transient_A>_views.xml
• |-- <main_transient_B>.py
• `-- <main_transient_B>_views.xml
Data files
• Odoo is a highly data driven system. Although
behavior is customized using Python code ,
part of a module's value is in the data it sets
up when loaded.
• Module data is declared via data files .
• Data files have to be declared in the manifest
file to be loaded, they can be declared in the
'data' list (always loaded) or in the 'demo'
list (only loaded in demonstration mode).
• XML files with <record> elements creates or
updates a database record.
XML files
To declare a record in XML, use the record
notation
• Place id attribute before model.
• For field declaration, name attribute is first.
Then place the value either in the field tag,
either in the eval attribute, and finally other
attributes (widget, options, ...) ordered by
importance.
• The tag <data> is only used to set not-updatable
data with noupdate=1. If there is only not-
updatable data in the file, the noupdate=1 can be
set on the <odoo> tag and do not set a <data> tag.
• <record id="view_id" model="ir.ui.view">
• <field name="name">view.name</field>
• <field name="model">object_name</field>
• <field name="priority" eval="16"/>
• <field name="arch" type="xml">
• <tree>
• <field name="my_field_1"/>
• <field name="my_field_2“
string="My Label“
widget="statusbar"
statusbar_visible="draft,sent,progress,done"/>
• </tree>
• </field>
• </record>
Odoo supports custom tags acting as
syntactic sugar:
• menuitem: use it as a shortcut to declare a
ir.ui.menu.
• template: use it to declare a QWeb View
requiring only the arch section of the view.
• report: use to declare a report action.
• act_window: use it if the record notation
can't do what you want.
Naming xml_id
• For a menu: <model_name>_menu
• For a view: <model_name>_view_<view_type>,
where view_type is kanban, form, tree,
search, ...
• For an action: the main action respects
<model_name>_action. Others are suffixed
with _<detail>, where detail is a lowercase
string briefly explaining the action. This is
used only if multiple actions are declared for
the model.
• For a group:
<model_name>_group_<group_name> where
group_name is the name of the group,
generally 'user', 'manager', ...
• For a rule:
<model_name>_rule_<concerned_group> where
concerned_group is the short name of the
concerned group ('user' for the
'model_name_group_user', 'public' for public
user, 'company' for multi-company rules, ...).
• <!-- views and menus -->
• <record id="model_name_view_form"
model="ir.ui.view">
...
• </record>
• <record id="model_name_view_kanban"
model="ir.ui.view">
...
• </record>
• <menuitem
id="model_name_menu_root"
name="Main Menu" sequence="5" />
• <menuitem
id="model_name_menu_action"
name="Sub Menu 1"
parent="module_name.module_name_menu_root“
action="model_name_action" sequence="10" />
• <!-- actions -->
• <record id="model_name_action"
model="ir.actions.act_window">
...
• </record>
• <record id="model_name_action_child_list"
model="ir.actions.act_window">
...
• </record>
• <!-- security -->
• <record id="module_name_group_user"
model="res.groups">
...
• </record>
• <record id="model_name_rule_public"
model="ir.rule">
...
• </record>
• <record id="model_name_rule_company"
model="ir.rule">
...
• </record>
Inherited view:
• The naming pattern of inherited view is
<base_view>_inherit_<current_module_name>. A
module may only extend a view once. Suffix the
original name with
_inherit_<current_module_name> where
current_module_name is the technical name of
the module extending the view.
<record
id="inherited_model_view_form_inherit_my_module"
model="ir.ui.view">
...
</record>
XML views
• Basic views:
Views define the way the records of a model
are displayed. Each type of view represents a
mode of visualization (a list of records, a graph
of their aggregation, …). Views can either be
requested generically via their type (e.g. a list
of partners) or specifically via their id. For
generic requests, the view with the correct
type and the lowest priority will be used (so the
lowest-priority view of each type is the default
view for that type).
Generic view declaration:
• A view is declared as a record of the model
ir.ui.view.
• The view type is implied by the root element
of the arch field
• The view's content is XML thus the arch field
must be declared as type="xml" to be parsed
correctly.
Tree views:
• Tree views, also called list views, display
records in a tabular form.
• Their root element is <tree>. The simplest
form of the tree view simply lists all the
fields to display in the table (each field as a
column):
<tree string="Idea list">
<field name="name"/>
<field name="inventor_id"/>
</tree>
Tree views can take supplementary attributes
to further customize their behavior:
• decoration-{$name} allow changing the style
of a row's text based on the corresponding
record's attributes.
• Values are Python expressions. For each
record, the expression is evaluated with the
record's attributes as context values and if
true, the corresponding style is applied to the
row. Other context values are uid (the id of
the current user) and current_date (the
current date as a string of the form yyyy-
MM-dd).
• {$name} can be bf (font-weight: bold), it
(font-style: italic), or any bootstrap
contextual color (danger, info, muted,
primary, success or warning).
• Editable :Either "top" or "bottom". Makes the
tree view editable in-place (rather than
having to go through the form view), the value
is the position where new rows appear.
• Invisible.
• <tree string="Idea Categories"
decoration-info="state=='draft'"
decoration-danger="state=='trashed'">
• <field name="name"/>
• <field name="state“
invisible="'product_id' not in context"/>/>
• </tree>
Form views:
• Forms are used to create and edit single
records.
• Their root element is <form>. They are
composed of high-level structure elements
(groups, notebooks) and interactive elements
(buttons and fields):
<form string="Idea form">
<group colspan="4">
<group colspan="2" col="2">
<separator string="General stuff" colspan="2"/>
<field name="name"/>
<field name="inventor_id"/>
</group>
<group colspan="2" col="2">
<separator string="Dates" colspan="2"/>
<field name="active"/>
<field name="invent_date" readonly="1"/>
</group>
<notebook colspan="4">
<page string="Description">
<field name="description" nolabel="1"/>
</page>
</notebook>
<field name="state"/>
</group> </form>
Domains
• In Odoo, Domains are values that encode
conditions on records. A domain is a list of
criteria used to select a subset of a model's
records. Each criteria is a triple with a field
name, an operator and a value.
• By default criteria are combined with an
implicit AND. The logical operators &(AND),
|(OR)and!(NOT) can be used to explicitly
combine criteria. They are used in prefix
position (the operator is inserted before its
arguments rather than between)
Search views:
• Search views customize the search field
associated with the list view (and other
aggregated views). Their root element is
<search> and they're composed of fields
defining which fields can be searched on:
<search>
<field name="name"/>
<field name="inventor_id"/>
</search>
• Search view <field> elements can have a
@filter_domain that overrides the domain
generated for searching on the given field. In
the given domain.
• Search views can also contain <filter> elements,
which act as toggles for predefined searches.
• Filters must have one of the following
attributes:
• Domain add the given domain to the current
search.
• Context add some context to the current
search; use the key group_by to group results on
the given field name.
<search string="Ideas">
<field name="name"/>
<field name="description“
string="Name and description“
filter_domain="['|', ('name', 'ilike', self),
('description', 'ilike', self)]"/>
<field name="inventor_id"/>
<field name="country_id"
widget="selection"/>
<filter name="my_ideas" string="My Ideas“
domain="[('inventor_id', '=', uid)]"/>
<group string="Group By">
<filter name="group_by_inventor"
string="Inventor"
context="{'group_by': 'inventor_id'}"/>
</group>
</search>
Graph views
• Graph views allow aggregated overview and
analysis of models, their root element is
<graph>.
• Graph views have 4 display modes, the default
mode is selected using the mandatory @type
attribute taking the values:
row (default)the field should be aggregated by
default.
Measure the field should be aggregated rather
than grouped on.
The display modes:
• Bar (default)a bar chart, the first dimension
is used to define groups on the horizontal
axis, other dimensions define aggregated bars
within each group.
• By default bars are side-by-side, they can be
stacked by using @stacked="True" on the
<graph>
• Line 2-dimensional line chart.
• Pie 2-dimensional pie
<graph string="Total idea score by Inventor">
<field name="inventor_id"/>
<field name="score" type="measure"/>
</graph>
Calendars:
• Displays records as calendar events. Their root
element is <calendar> and their most common
attributes are:
• colorThe name of the field used for color
segmentation. Colors are automatically
distributed to events, but events in the same
color segment (records which have the same
value for their @color field) will be given the
same color.
• date_start record's field holding the start
date/time for the event.
• date_stop (optional)record's field holding the
end date/time for the event
• <!-- calendar view -->
• <record model="ir.ui.view"
id="session_calendar_view">
• <field name="name">session.calendar</field>
<field name="model">openacademy.session</field>
<field name="arch" type="xml">
• <calendar string="Session Calendar"
date_start="start_date"
date_stop="end_date“
color="instructor_id">
• <field name="name"/>
• </calendar>
• </field>
• </record>
…
• <record model="ir.actions.act_window"
id="session_list_action">
• <field name="name">Sessions</field>
• <field
name="res_model">openacademy.session</field>
<field name="view_type">form</field>
• <field
name="view_mode">tree,form,calendar</field>
</record>
…
• Kanban:
• Used to organize tasks, production processes,
etc… their root element is <kanban>.
• A kanban view shows a set of cards possibly
grouped in columns. Each card represents a
record, and each column the values of an
aggregation field.
• Kanban views define the structure of each
card as a mix of form elements (including
basic HTML) and Qweb.
<record model="ir.ui.view"
id="view_openacad_session_kanban">
<fieldname="name">openacad.session.kanban</field>
<field name="model">openacademy.session</field>
<field name="arch" type="xml">
<kanban default_group_by="course_id">
<field name="color"/>
<templates>
<t t-name="kanban-box">
<div t-attf-class=
"oe_kanban_color_{{kanban_getcolor(record.color.
raw_value)}} oe_kanban_global_click_edit
oe_semantic_html_override oe_kanban_card
{{record.group_fancy==1 ? 'oe_kanban_card_fancy'
: ''}}">
<div class="oe_dropdown_kanban">
<!-- dropdown menu -->
<div class="oe_dropdown_toggle">
<i class="fa fa-bars fa-lg"/>
<ul class="oe_dropdown_menu">
<li>
<a type="delete">Delete</a>
</li>
<li>
<ul class="oe_kanban_colorpicker" data-
field="color"/>
</li>
</ul>
</div>
<div class="oe_clear">
</div>
</div>
<div t-attf-class="oe_kanban_content">
<!-- title -->
Session name:
<field name="name"/> <br/>
Start date:
<field name="start_date"/> <br/>
duration:
<field name="duration"/>
</div> </div>
</t>
</templates> </kanban> </field> </record>
View inheritance
• Instead of modifying existing views in place
(by overwriting them), Odoo provides view
inheritance where children "extension" views
are applied on top of root views, and can add
or remove content from their parent.
• An extension view references its parent using
the inherit_id field, and instead of a single
view its arch field is composed of any number
of xpath elements selecting and altering the
content of their parent view.
• Expr:An XPath expression selecting a single
element in the parent view. Raises an error if
it matches no element or more than one
position Operation to apply to the matched
element.
• Inside:appends xpath's body at the end of
the matched element.
• Replace: replaces the matched element with
the xpath's body, replacing any $0 node
occurrence in the new body with the original
element
• Before:inserts the xpath's body as a sibling
before the matched element.
• After: inserts the xpaths's body as a sibling
after the matched element.
• Attributes : alters the attributes of the
matched element using special attribute
elements in the xpath's body.
<!-- improved idea categories list -->
• <record id="idea_category_list2"
model="ir.ui.view">
• <field name="name">id.category.list2</field>
<field name="model">idea.category</field>
<field name="inherit_id"
ref="id_category_list"/>
• <field name="arch" type="xml">
<!-- find field description and add the field idea_ids
after it -->
• <xpath expr="//field[@name='description']"
position="after">
• <field name="idea_ids" string="Number of
ideas"/>
• </xpath>
• </field>
• </record>
Security In
Odoo
Agenda
- CSRF .
- CSRF In Odoo
- Odoo in security .
- Odoo Login .
What is Cross Site Request
Forgery (CSRF)?
Cross-site request forgery (CSRF)
vulnerabilities can be used to trick a user’s
browser into performing an unwanted action
on your site.
How Attack Can Happen?
Damaged Causes By CSRF:
 In Net-banking attacker can forge the request
and send it to victim to steal money from
Victim’s account .
 Personal health information can be stolen or
modified in a hospital database .
 Attacker force victim to perform unwanted
action which affect their profile .
Mitigation Techniques:
Can be mitigate by two ways
* CSRF token.
* Captcha.
CSRF In Odoo:
You must add this line of code in your
form :
`csrf_token` e.g. :
<input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
What Is Odoo Security?
It’s ability to control what user can
do and what user can't-do on a
different level .
Have four basic operations: read,
write, create, and unlink(Delete) .
Why would I want to have field
level access control in Odoo?
 Restrict temporary or part-time workers from
data they do not need to see.
 It makes the system easier to use and the forms
less cluttered.
 It's important to learn all aspects of Odoo's access
rights before configuring Odoo for production.
Security mechanisms in Odoo:
Groups.
Access Control.
Record Rules.
Filed Access.
Groups:
How to assign users to groups?
Security access in Odoo is
configured through security
groups: permissions are given to
groups and then groups are
assigned to users.
Why should I use groups to
restrict access rather than
removing the fields?
No. This is a bad idea because Odoo may
have processes and other depencencies that
are expecting that field to be available on
the form.
Go to Settings > Groups
Here you can see, you can add as
many as users under Users tab so that
only that users can view
Accounting&Finance/Billing.
Access Control List:
 In Odoo, views and menus are restricted to a user due to
access right permission. Only admin has right to view all
records. Access right permission is managed by creating an
ir.model.access.csv file.
 This file can Grant Available permissions are :
 creation (perm_create).
 searching and reading (perm_read).
 updating existing records (perm_write).
 deleting existing records (perm_unlink).
 Define group to a model(optional) :
– If no group: access rights applies to all users
– If group: access rights applies to member of that group
 Access controls are additive, for example if the user
belongs to one group which allows writing and another
which allows deleting, they can both write and delete.
 Here is the steps define ir.model.access.csv file for custom
model:
Step 1 : Create Security folder in your custom module.
 Blog/security
Step 2 : Make ir.model.access.csv file in Security folder.
 Blog/security/ir.model.access.csv
Step3 : Edit in __manifest__.py
'data': [
'security/ir.model.access.csv',
],
Step4 : Write following code in your
ir.model.access.csv
 Defining Access Rights ( ir.model.access.csv )
 id = unique identity for the permission (Example:access_blog_post_user)
 name = unique name for the permission (Example:blog.post.user)
 model_id/id = the model unique name of the class you want apply
permission on (Example: model_blog_post)
 group_id/id = Permission apply on group(Example:
Blog.group_blog_user)
 Where Blog:module name , group_blog_user :group id
 perm_read,perm_write,perm_create,perm_unlink = the 4 values for the
relative permission to read, write,create,unlink record on defined class. 1 is
True and 0 is False
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_blog_post_user,blog.post.user,model_blog_post,Blog.group_blog_user,1,0,0,0
Record Rules:
 Record Rules are certain conditions that the records must
satisfy for the operations such as : (read,write,delet,create)
to be allowed.
 it is applied , record-by-record after the access control has
been applied.
 Record Rules can be defined from the menu also without
creating any file.
 A set of permissions to which it applies (e.g. if perm_read is
set, the rule will only be checked when reading a record)
 A set of user groups (no group means global rule)
 A domain for filtering data
 If filter matches: It is accessible
 If filter does not matches: It is not accessible
Go to Settings > Security>Record
Rules:
Field Access
An ORM field can have a groups attribute
providing a list of groups.If the current user is
not in one of the listed groups, he will not have
access to the field:
e.g:
Log In!
Dose Odoo Store Passwords in
Clear text??!!
 Yes by default it does, you can change this behavior if
you install the module auth_crypt .
 But as we all know that in term of security it is a very
bad practice to store passwords without strong hashing
(SHA-256+) and salting!
What Odoo say about this?
 Well, actually that's a feature, so that it's possible to
recover lost passwords.
 As for the reason for cleartext passwords: once you
switch to encrypted passwords you can't recover user
passwords anymore . So enabling it is a choice, because
there's no going back. We don't currently plan to make
passwords encrypted by default.
ORM API
Odoo 11
Contents
• What we mean by ORM in odoo?
• Structural attributes.
• Fields.
• Method decorators.
• Common ORM methods.
• Domains.
• Inheritance.
What we mean by ORM in odoo?
• In Odoo, the data model is described and
manipulated through Python classes and objects.
It is the ORM job to bridge the gap - as
transparently as possible for the developer -
between Python and the underlying relational
database (PostgreSQL), which will provide the
persistence we need for our objects. And as we
know “Every thing in Odoo is an object”.
• A key component of Odoo is the ORM layer. This layer avoids having
to write most SQL by hand and provides extensibility and security
services.
• Business objects are declared as Python classes
extending model which integrates them into the automated
persistence system.
• Models can be configured by setting a number of attributes at their
definition. The most important attribute is _name which is required
and defines the name for the model in the Odoo system. Here is a
minimally complete definition of a model:
The system will later instantiate the class once per database (on
which the class' module is installed).
Structural attributes
• _name :
business object name, in dot-notation (in module namespace) .
• _rec_name:
Alternative field to use as name, used by osv’s name_get() (default: 'name').
• _inherit:
If _name is set, names of parent models to inherit from. Can be a str if
inheriting from a single parent
If _name is unset, name of a single model to extend in-place
Structural attributes
• _inherits :
dictionary mapping the _name of the parent
business objects to the names of the
corresponding foreign key fields to use:
Structural attributes
• _order :
Ordering field when searching without an
ordering specified (default: 'id')
Structural attributes
• _auto:
Whether a database table should be created (default:
True)
• _table:
Name of the table backing the model created when
_auto, automatically generated by default.
Structural attributes
• _constraints
• list of (constraint_function, message, fields)
defining Python constraints. The fields list is
indicative
Deprecated since version 8.0: use constrains().
Structural attributes
• _sql_constraints
list of (name, sql_definition, message) triples
defining SQL constraints to execute when
generating the backing table
Fileds
• Fields are used to define what the model can store
and where. Fields are defined as attributes on the
model class:
• Simple fields :
fields.Char
fields.Integer
fields.Float
fields.Date
fields.Selection :
When extending a model, if you want to add possible values to a selection
field, you may use the selection_add keyword :
fields.Text
fields.Boolean
fields.Monetary
fields.Html: Used to store HTML, provides an HTML widget.
• Reserved fields:
Odoo creates a few fields in all models. These fields are managed by the
system and shouldn't be written to. They can be read if useful or
necessary:
 id (Id)The unique identifier for a record in its model.
 create_date (Datetime)Creation date of the record.
 create_uid (Many2one)User who created the record.
 write_date (Datetime)Last modification date of the record.
 write_uid (Many2one)user who last modified the record.
 This information is available from the web client, navigating to the
Developer Mode menu and selecting the View Metadata option.
• Computed Fields :
 Fields can be computed (instead of read straight from the database)
using the compute parameter. It must assign the computed value to the
field. If it uses the values of other fields, it should specify those fields
using depends() :
 computed fields are not stored by default, they are computed and
returned when requested. Setting store=True will store them in the
database and automatically enable searching.
The decorator odoo.api.depends() must be applied on the compute
method to specify the field dependencies
to allow setting values on a computed field, use the inverse parameter. It is
the name of a function reversing the computation and setting the
relevant fields.
 multiple fields can be computed at the same time by the same method,
just use the same method on all fields and set all of them :
• The computed field can be read, but it can't
be searched or written. To enable these
operations, we first need to implement
specialized functions for them. Along with the
compute function, we can also set a search
function, implementing the search logic, and
the inverse function, implementing the write
logic.
• Related fields :
A special case of computed fields are related (proxy) fields, which provide
the value of a sub-field on the current record. They are defined by
setting the related parameter and like regular computed fields they
can be stored.
• Behind the scenes, related fields are just computed fields that
conveniently implement search and inverse methods. This means that
we can search and write on them out of the box, without having to
write any additional code.
• onchange: updating UI on the fly :
• When a user changes a field's value in a form
(but hasn't saved the form yet), it can be
useful to automatically update other fields
based on that value e.g. updating a final total
when the tax is changed or a new invoice line
is added.
• computed fields are automatically checked
and recomputed, they do not need an
onchange
• for non-computed fields, the onchange()
decorator is used to provide new field values
• Common attributes :
There are many attributes may be provided when instantiating a
field as a common attributes :
String :
the label of the field seen by users (string); if not set, the ORM takes
the field name in the class (capitalized).
Help:
the tooltip of the field seen by users (string)
Readonly:
whether the field is readonly (boolean, by default False)
Required:
whether the value of the field is required (boolean, by default False)
Index:
whether the field is indexed in database (boolean, by default False)
Common fields attributes
default :
the default value for the field; this is either a static value, or a
function taking a recordset and returning a value; use
default=None to discard default values for the field.
states :
a dictionary mapping state values to lists of UI attribute-value
pairs; possible attributes are: 'readonly', 'required',
'invisible'. Note: Any state-based condition requires the
state field value to be available on the client-side UI. This is
typically done by including it in the relevant views, possibly
made invisible if not relevant for the end-user.
groups :
comma-separated list of group xml ids (string); this restricts the field access
to the users of the given groups only
copy (bool) :
whether the field value should be copied when the record is duplicated
(default: True for normal fields, False for one2many and computed fields,
including property fields and related fields)
oldname (string):
the previous name of this field, so that ORM can rename it automatically at
migration
Translate(bool) :
In case of True it means can be translated
size (int):
the maximum size of values stored for that field
• Relational fields :
1. Many2one :
The many2one relationship accepts two positional arguments: the related
model (corresponding to the comodel keyword argument) and the title
string. It creates a field in the database table with a foreign key to the
related table.
Parameters :
• comodel_name : name of the target model (string) ‘mandotary’
• domain : an optional domain to set on candidate values on the client
side (domain or string)
• context : an optional context to use on the client side when handling
that field (dictionary)
• ondelete : what to do when the referred record is deleted; possible
values are: 'set null', 'restrict', 'cascade'
• auto_join : whether JOINs are generated upon search through that field
(boolean, by default False)
• delegate : set it to True to make fields of the target model accessible
from the current model (corresponds to _inherits)
2. One2many :
An inverse of many2one can be added to the other end of the relationship. This has
no impact on the actual database structure, but allows us easily browse from the
one side of the many related records. A typical use case is the relationship
between a document header and its lines.
One2many makes it easy for a parent to keep track of its children.
• Parameters :
comodel_name : name of the target model (string)
inverse_name : name of the inverse Many2one field in comodel_name (string)
domain : an optional domain to set on candidate values on the client side (domain
or string)
context : an optional context to use on the client side when handling that field
(dictionary)
auto_join : whether JOINs are generated upon search through that field (boolean,
by default False)
limit : optional limit to use upon read (integer)
(Comodel_name + inverse_name ) are mandatory fields.
3.Many2many :
At the database level, it does not add any columns to the existing tables. Instead, it
automatically creates a new relationship table that has only two ID fields with the foreign
keys for the related tables. The relationship table name and the field names are
automatically generated. The relationship table name is the two table names joined with an
underscore with _rel appended to it.
Parameters
• comodel_name : name of the target model (string) ‘mandatory’
• Parameters
• relation : optional name of the table that stores the relation in the database (string)
• column1 : optional name of the column referring to "these" records in the table relation
(string)
• column2 : optional name of the column referring to "those" records in the table relation
(string)
• domain : an optional domain to set on candidate values on the client side (domain or string)
• context : an optional context to use on the client side when handling that field (dictionary)
• limit : optional limit to use upon read (integer)
Method decorators
• Before we go to decorators we need first to know little things about
recordest
• Recordset :
New in version 8.0 , Interaction with models and records is performed
through recordsets, a sorted set of records of the same model.
Methods defined on a model are executed on a recordset, and their self is
a recordset
• Record cache and prefetching :
Odoo maintains a cache for the fields of the records, so that not every
field access issues a database request, which would be terrible for
performance. The following example queries the database only for the
first statement:
To avoid reading one field on one record at a time, Odoo prefetches
records and fields following some heuristics to get good performance.
Once a field must be read on a given record, the ORM actually reads
that field on a larger recordset, and stores the returned values in cache
for later use. The prefetched recordset is usually the recordset from
which the record comes by iteration. Moreover, all simple stored fields
(boolean, integer, float, char, text, date, datetime, selection,
many2one) are fetched altogether; they correspond to the columns of
the model's table, and are fetched efficiently in the same query.
Method decorators
• decorators are important for the server to know how to handle the
method.
• There are two different API styles, namely the "traditional" and "record"
styles.
• In the "traditional" style, parameters like the database cursor, user id,
context dictionary and record ids (usually denoted as cr, uid, context, ids)
are passed explicitly to all methods. In the "record" style, those
parameters are hidden into model instances, which gives it a more object-
oriented feel.
• A decorator is a function that takes a function as input and returns a
function.
• The anatomy of the decorator is: @decorator-expression
• Decorator-expression is an expression that returns a callable thing. The
callable thing has to take a single argument. Function definition is a
function definition (it, therefore, must begin with def).
• In older version of odoo, we use a cursor, uid, context and ids for defining
all method.
• In odoo 9, odoo 10 we use self as the parameter when defining a method
with certain method decorators.This decorator are passed the parameters
explicitly to the method. Which provide a smooth way to write functions
and avoid complications.
• 1.@api.one:
It is specific for one record and cannot be used for multiple
records. Self is redefined as current record.
Example
@api.one
def get_product(self):
self.product_name = ‘desktop’
This function will automatically write product name field of each
record with ‘desktop’.
• 2.@api.multi:
It can use for multiple records, so we can
loop through it. Here Self-contains
recordset so that we need for loop for
iterating through each record.
Example
@api.multi
def get_product(self):
For the record in self:
self.product_name = ‘desktop’
• 3.@api.model:
This decorator will convert old API calls to decorated function to new
API signature.
• 4.@api.depends:
This decorator is specifically used for computing fields in odoo. The
decorator function works only if any of the fields specified in the
@api.depends is changed in the form.
Dependencies can be dotted paths when using sub-fields.
Example:
@api.depends(‘partner_id.street’)
def _get_street(self):
for record in self:
for line in record.partner_id:
record.street = line.street
Computed field are not stored by default, they have computed the
function and return the value.We use store = True to store the
computed value to the database.
• 5.@api.onchange:
This decorator will avoid the on change attribute in the xml file.
The fields are written as the parameter of the function.
Example:
@api.onchange(‘date_of_birth’,’age’)
def onchange_age_calculation(self ):
if not self.date_of_birth:
self.age = 0
else:
today_date = datetime.now().year
date_split = self.date_of_birth.split(‘-‘,1)
birth_year = date_split[0]
self.age = today_date -int(birth_year)
This function will automatically write age field when changing
the value of date_of_birth field in form view.
• 6.@api.constrains:
This decorator will ensure that decorated
function will be called on creating, write,
unlink operation. It will act as a constraint
checker. This will especially use for warning
messages and validation.
Common ORM methods
• search() : Takes a search domain, returns a
recordset of matching records:
• create() : Takes a number of field values,
and returns a recordset containing the
record created
• write()Takes a number of field values,
writes them to all the records in its
recordset. Does not return anything:
• browse()Takes a database id or a list of ids
and returns a recordset:
• ensure_one() checks that the recordset is a
singleton (only a single record), raises an
error otherwise:
Domains
• A domain is a list of criteria, each criterion
being a triple (either a list or a tuple) of
(field_name, operator, value) where:
• field_name (str) :
a field name of the current model, or a
relationship traversal through a Many2one
using dot-notation e.g. 'street' or
'partner_id.country'operator (str)an
operator used to compare the field_name
with the value.
• operator (str) :
an operator used to compare the field_name with the value. Valid operators are:
1. =equals to
2. !=not equals to
3. > greater than
4. >= greater than or equal to
5. <less than
6. <=less than or equal to
7. =?unset or equals to (returns true if value is either None or False, otherwise behaves like
=)
8. =like : matches field_name against the value pattern. An underscore _ in the pattern
stands for (matches) any single character; a percent sign % matches any string of zero or
more characters.
9. Like matches field_name against the %value% pattern. Similar to =like but wraps value
with '%' before matching
10. not like doesn't match against the %value% pattern
11. Ilike case insensitive like
12. not ilike case insensitive not like
13. =ilike case insensitive =like
14. In is equal to any of the items from value, value should be a list of items
15. not in is unequal to all of the items from value
16. child_of is a child (descendant) of a value record.
17. Takes the semantics of the model into account (i.e following the relationship field named
by _parent_name).
• Value
variable type, must be comparable (through operator) to the named field
• Domain criteria can be combined using logical operators in prefix
form:
• & : logical AND, default operation to combine criteria following one
another. Arity 2 (uses the next 2 criteria or combinations).
• | : logical OR.
• ! : logical NOT.
Inheritance
• Odoo provides three different mechanisms to extend models in a modular way:
 Classical inheritance :
When use (_inherit + _name) = the new model will use the existing model
 Extension inheritance :
When use (_inherit) without (_name) in new model it will replace the existing one
 Delegation inheritance :
The third inheritance mechanism provides more flexibility (it can be altered at
runtime) but less power: using the _inherits a model delegates the lookup of
any field not found on the current model to "children" models. The delegation
is performed via Reference fields automatically set up on the parent model.(in
this type only fields are inherited)
Classical inheritance
Extension Inheritance
Delegation Inheritance
Done By:
Zaineb Alnzeer
Esra Adil
Amel Salah
Rawan Mohiealdeen
NCTR Company.
E-Service Department.

Weitere ähnliche Inhalte

Was ist angesagt?

Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkOdoo
 
Deploying & Scaling your Odoo Server
Deploying & Scaling your Odoo ServerDeploying & Scaling your Odoo Server
Deploying & Scaling your Odoo ServerOdoo
 
scaffold method odoo 16
scaffold method odoo 16scaffold method odoo 16
scaffold method odoo 16Celine George
 
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...Celine George
 
Set Default Values to Fields in Odoo 15
Set Default Values to Fields in Odoo 15Set Default Values to Fields in Odoo 15
Set Default Values to Fields in Odoo 15Celine George
 
Defining Kanban View in Odoo15 | Advanced Views
Defining Kanban View in Odoo15 | Advanced ViewsDefining Kanban View in Odoo15 | Advanced Views
Defining Kanban View in Odoo15 | Advanced ViewsCeline George
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlOdoo
 
Updating Client Interface 'on change' @api.onchange in Odoo 15
Updating Client Interface 'on change' @api.onchange in Odoo 15Updating Client Interface 'on change' @api.onchange in Odoo 15
Updating Client Interface 'on change' @api.onchange in Odoo 15Celine George
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code HardeningOdoo
 
How to Define Many2many Field in Odoo 15
How to Define Many2many Field in Odoo 15How to Define Many2many Field in Odoo 15
How to Define Many2many Field in Odoo 15Celine George
 
How to Use Constraint and SQL Constraint in Odoo 15
How to Use Constraint and SQL Constraint in Odoo 15How to Use Constraint and SQL Constraint in Odoo 15
How to Use Constraint and SQL Constraint in Odoo 15Celine George
 
Odoo External API
Odoo External APIOdoo External API
Odoo External APIOdoo
 
Name Search() Function in Odoo 16
Name Search() Function in Odoo 16Name Search() Function in Odoo 16
Name Search() Function in Odoo 16Celine George
 
Best Practices in Handling Performance Issues
Best Practices in Handling Performance IssuesBest Practices in Handling Performance Issues
Best Practices in Handling Performance IssuesOdoo
 
What is Delegation Inheritance in Odoo 15
What is Delegation Inheritance in Odoo 15What is Delegation Inheritance in Odoo 15
What is Delegation Inheritance in Odoo 15Celine George
 
The Odoo JS Framework
The Odoo JS FrameworkThe Odoo JS Framework
The Odoo JS FrameworkOdoo
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in OdooOdoo
 
Odoo icon smart buttons
Odoo   icon smart buttonsOdoo   icon smart buttons
Odoo icon smart buttonsTaieb Kristou
 
Oracle Forms Triggers
Oracle Forms TriggersOracle Forms Triggers
Oracle Forms TriggersSekhar Byna
 

Was ist angesagt? (20)

Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo Framework
 
Deploying & Scaling your Odoo Server
Deploying & Scaling your Odoo ServerDeploying & Scaling your Odoo Server
Deploying & Scaling your Odoo Server
 
scaffold method odoo 16
scaffold method odoo 16scaffold method odoo 16
scaffold method odoo 16
 
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
 
Set Default Values to Fields in Odoo 15
Set Default Values to Fields in Odoo 15Set Default Values to Fields in Odoo 15
Set Default Values to Fields in Odoo 15
 
Defining Kanban View in Odoo15 | Advanced Views
Defining Kanban View in Odoo15 | Advanced ViewsDefining Kanban View in Odoo15 | Advanced Views
Defining Kanban View in Odoo15 | Advanced Views
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
 
Updating Client Interface 'on change' @api.onchange in Odoo 15
Updating Client Interface 'on change' @api.onchange in Odoo 15Updating Client Interface 'on change' @api.onchange in Odoo 15
Updating Client Interface 'on change' @api.onchange in Odoo 15
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
How to Define Many2many Field in Odoo 15
How to Define Many2many Field in Odoo 15How to Define Many2many Field in Odoo 15
How to Define Many2many Field in Odoo 15
 
How to Use Constraint and SQL Constraint in Odoo 15
How to Use Constraint and SQL Constraint in Odoo 15How to Use Constraint and SQL Constraint in Odoo 15
How to Use Constraint and SQL Constraint in Odoo 15
 
Odoo External API
Odoo External APIOdoo External API
Odoo External API
 
Name Search() Function in Odoo 16
Name Search() Function in Odoo 16Name Search() Function in Odoo 16
Name Search() Function in Odoo 16
 
Best Practices in Handling Performance Issues
Best Practices in Handling Performance IssuesBest Practices in Handling Performance Issues
Best Practices in Handling Performance Issues
 
What is Delegation Inheritance in Odoo 15
What is Delegation Inheritance in Odoo 15What is Delegation Inheritance in Odoo 15
What is Delegation Inheritance in Odoo 15
 
The Odoo JS Framework
The Odoo JS FrameworkThe Odoo JS Framework
The Odoo JS Framework
 
Oracle Apps - Forms
Oracle Apps - FormsOracle Apps - Forms
Oracle Apps - Forms
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Odoo icon smart buttons
Odoo   icon smart buttonsOdoo   icon smart buttons
Odoo icon smart buttons
 
Oracle Forms Triggers
Oracle Forms TriggersOracle Forms Triggers
Oracle Forms Triggers
 

Ähnlich wie Odoo (Build module, Security, ORM)

External dependencies ,pre init hook &amp; post init hook in odoo
External dependencies ,pre init hook &amp; post init hook in odooExternal dependencies ,pre init hook &amp; post init hook in odoo
External dependencies ,pre init hook &amp; post init hook in odooCeline George
 
How to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold MethodHow to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold MethodCeline George
 
Module Structure in Odoo 15
Module Structure in Odoo 15Module Structure in Odoo 15
Module Structure in Odoo 15Celine George
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxAgusto Sipahutar
 
Odoo 15 Composition of Module
Odoo 15 Composition of ModuleOdoo 15 Composition of Module
Odoo 15 Composition of ModuleCeline George
 
Open erp technical_memento_v0.6.3_a4
Open erp technical_memento_v0.6.3_a4Open erp technical_memento_v0.6.3_a4
Open erp technical_memento_v0.6.3_a4openerpwiki
 
Introduction And Basics of Modules in Drupal 7
Introduction And Basics of Modules in Drupal 7 Introduction And Basics of Modules in Drupal 7
Introduction And Basics of Modules in Drupal 7 Dhinakaran Mani
 
OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015Oro Inc.
 
Composition of a Module in Odoo 16
Composition of a Module in Odoo 16Composition of a Module in Odoo 16
Composition of a Module in Odoo 16Celine George
 
Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.DrupalCamp Kyiv
 
How to Create Manifest File in Odoo 17 ERP
How to Create Manifest File in Odoo 17 ERPHow to Create Manifest File in Odoo 17 ERP
How to Create Manifest File in Odoo 17 ERPCeline George
 
OpenERP Technical Memento V0.7.3
OpenERP Technical Memento V0.7.3OpenERP Technical Memento V0.7.3
OpenERP Technical Memento V0.7.3Borni DHIFI
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical MementoOdoo
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxAgusto Sipahutar
 
Must be similar to screenshotsI must be able to run the projects.docx
Must be similar to screenshotsI must be able to run the projects.docxMust be similar to screenshotsI must be able to run the projects.docx
Must be similar to screenshotsI must be able to run the projects.docxherthaweston
 
Mageguru - magento custom module development
Mageguru -  magento custom module development Mageguru -  magento custom module development
Mageguru - magento custom module development Mage Guru
 

Ähnlich wie Odoo (Build module, Security, ORM) (20)

External dependencies ,pre init hook &amp; post init hook in odoo
External dependencies ,pre init hook &amp; post init hook in odooExternal dependencies ,pre init hook &amp; post init hook in odoo
External dependencies ,pre init hook &amp; post init hook in odoo
 
How to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold MethodHow to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold Method
 
Module Structure in Odoo 15
Module Structure in Odoo 15Module Structure in Odoo 15
Module Structure in Odoo 15
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptx
 
Odoo 15 Composition of Module
Odoo 15 Composition of ModuleOdoo 15 Composition of Module
Odoo 15 Composition of Module
 
D8 training
D8 trainingD8 training
D8 training
 
Open erp technical_memento_v0.6.3_a4
Open erp technical_memento_v0.6.3_a4Open erp technical_memento_v0.6.3_a4
Open erp technical_memento_v0.6.3_a4
 
Introduction And Basics of Modules in Drupal 7
Introduction And Basics of Modules in Drupal 7 Introduction And Basics of Modules in Drupal 7
Introduction And Basics of Modules in Drupal 7
 
OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015OroCRM Partner Technical Training: September 2015
OroCRM Partner Technical Training: September 2015
 
Composition of a Module in Odoo 16
Composition of a Module in Odoo 16Composition of a Module in Odoo 16
Composition of a Module in Odoo 16
 
Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.
 
How to Create Manifest File in Odoo 17 ERP
How to Create Manifest File in Odoo 17 ERPHow to Create Manifest File in Odoo 17 ERP
How to Create Manifest File in Odoo 17 ERP
 
10team
10team10team
10team
 
OpenERP Technical Memento V0.7.3
OpenERP Technical Memento V0.7.3OpenERP Technical Memento V0.7.3
OpenERP Technical Memento V0.7.3
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical Memento
 
Drupal
DrupalDrupal
Drupal
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptx
 
Must be similar to screenshotsI must be able to run the projects.docx
Must be similar to screenshotsI must be able to run the projects.docxMust be similar to screenshotsI must be able to run the projects.docx
Must be similar to screenshotsI must be able to run the projects.docx
 
Mageguru - magento custom module development
Mageguru -  magento custom module development Mageguru -  magento custom module development
Mageguru - magento custom module development
 
Drupal Modules
Drupal ModulesDrupal Modules
Drupal Modules
 

Kürzlich hochgeladen

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 

Kürzlich hochgeladen (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 

Odoo (Build module, Security, ORM)

  • 2. Build an Odoo module
  • 3. Outlines: • Modularity • Module structure in odoo • Manifest file • Xml with odoo
  • 4. Modularity • Modular programming is a software design technique to split your code into separate parts. These parts are called modules. The focus for this separation should be to have modules with no or just few dependencies upon other modules. • The executable application will be created by putting the modules together.
  • 5. • Advantages: • Readable • reliable • reusable • easier to debug and manage
  • 6. Do not reinvent the wheel !! • Before beginning a new module development, find out if there is any module that might solve your problem totally or partially. • If you decide to develop a new module, analyze what features you will need in other modules, and try to encapsulate them in other module so that you can inherit them later
  • 7. Module structure in odoo Directories: • A module is organized in important directories that contain the business logic. • Module directories are specified by using the –-addons-path.py option. • An Odoo module is declared by its manifest. • The manifest file serves to declare a python package as an Odoo module and to specify module metadata.
  • 8. • A module is also a Python package with a __init__.py file, containing import instructions for various Python files in the module.
  • 9. Directories • data/ : demo and data xml • models/ : models definition • controllers/ : contains controllers (HTTP routes). • views/ : contains the views and templates • static/ : contains the web assets, separated into css/, js/, img/, lib/, ...
  • 10. Other optional directories compose the module: wizard/ : regroups the transient models (formerly osv_memory) and their views. report/ : contains the reports (RML report [deprecated], models based on SQL views (for reporting) and other complex reports). Python objects and XML views are included in this directory. tests/ : contains the Python/YML tests Security/ i18n/: used for translating
  • 11. Odoo follows an MVC-like architecture: • The model layer, defining the structure of the app's data. • The view layer, describing the user interface • The controller layer, supporting the business logic of the application
  • 12. Odoo provides a mechanism to help set up a new module, odoo-bin has a subcommand scaffold to create an empty module: odoo-bin scaffold <module name> <where to put it> Starting with odoo
  • 13. Configuring the addons path: • The Odoo server has a configuration option called addons_path to set where the server should look for modules. By default, this points to the /addons directory, where the Odoo server is running. • We can provide not only one, but a list of directories where modules can be found. This allows us to keep our custom modules in a different directory, without having them mixed with the official addons. $ ./odoo-bin -d demo –addons path="../custom_addons_app,./addons"
  • 14. Manifest content • name (str, required)the human-readable name of the module . • version (str)this module's version, should follow semantic versioning rules . • description (str)extended description for the module. • author (str)name of the module author. • website (str)website URL for the module author. • license (str, defaults: LGPL-3)distribution license for the module
  • 15. category (str, default: Uncategorized) classification category within Odoo, rough business domain for the module. Although using existing categories is recommended, the field is freeform and unknown categories are created on-the-fly. data (list(str))List of data files which must always be installed or updated with the module. A list of paths from the module root directory.
  • 16. demo (list(str))List of data files which are only installed or updated in demonstration mode. installable (bool default: False)Whether a user should be able to install the module from the Web UI or not. auto_install (bool, default: False)If True, this module will automatically be installed if all of its dependencies are installed. external_dependencies (dict(key=list(str)))A dictionary containing python and/or binary dependencies.
  • 17. depends (list(str))Odoo modules which must be loaded before this one, either because this module uses features they create or because it alters resources they define . When a module is installed, all of its dependencies are installed before it. Likewise dependencies are loaded before a module is loaded. application (bool, default: False)Whether the module should be considered as a fully- fledged application (True) or is just a technical module (False) that provides some extra functionality to an existing application module.
  • 18. css (list(str))Specify css files with custom rules to be imported, these files should be located in static/src/css inside the module. images (list(str))Specify image files to be used by the module. maintainer (str)Person or entity in charge of the maintenance of this module, by default it is assumed that the author is the maintainer.
  • 19. {pre_init, post_init, uninstall}_hook (str)Hooks for module installation/uninstallation, their value should be a string representing the name of a function defined inside the module's __init__.py. pre_init_hook takes a cursor as its only argument, this function is executed prior to the module's installation.
  • 20. post_init_hook takes a cursor and a registry as its arguments, this function is executed right after the module's installation. uninstall_hook takes a cursor and a registry as its arguments, this function is executed after the module's uninstallation. These hooks should only be used when setup/cleanup required for this module is either extremely difficult or impossible through the api.
  • 21. File naming • For views declarations, split backend views from (frontend) templates in 2 different files. • For models, split the business logic by sets of models, in each set select a main model, this model gives its name to the set. If there is only one model, its name is the same as the module name.
  • 22. For each set named <main_model> the following files may be created: • models/<main_model>.py • models/<inherited_main_model>.py • views/<main_model>_templates.xml • views/<main_model>_views.xml
  • 23. • For data, split them by purpose : demo or data. The filename will be the main_model name, suffixed by _demo.xml or _data.xml. • For controllers, the only file should be named main.py. Otherwise, if you need to inherit an existing controller from another module, its name will be <module_name>.py. Unlike models, each controller class should be contained in a separated file.
  • 24. • For static files, since the resources can be used in different contexts (frontend, backend, both), they will be included in only one bundle. So, CSS/Less, JavaScript and XML files should be suffixed with the name of the bundle type. • Don't link data (image, libraries) outside Odoo: do not use an URL to an image but copy it in our codebase instead.
  • 25. • addons/<my_module_name>/ • |-- __init__.py • |-- __manifest__.py • |-- controllers/ • | |-- __init__.py • | |-- <inherited_module_name>.py • | `-- main.py • |-- data/ • | |-- <main_model>_data.xml • | `-- <inherited_main_model>_demo.xml • |-- models/ • | |-- __init__.py • | |-- <main_model>.py • | `-- <inherited_main_model>.py
  • 26. • |-- report/ • | |-- __init__.py • | |-- <main_stat_report_model>.py • | |-- <main_stat_report_model>_views.xml • | |-- <main_print_report>_reports.xml • | `-- <main_print_report>_templates.xml • |-- security/ • | |-- ir.model.access.csv • | `-- <main_model>_security.xml
  • 27. • |-- static/ • | |-- img/ • | | |-- my_little_kitten.png • | | `-- troll.jpg • | |-- lib/ • | | `-- external_lib/ • | `-- src/ • | |-- js/ • | | `-- <my_module_name>.js • | |-- css/ • | | `-- <my_module_name>.css • | |-- less/ • | | `-- <my_module_name>.less • | `-- xml/ • | `-- <my_module_name>.xml
  • 28. • |-- views/ • | |-- <main_model>_templates.xml • | |-- <main_model>_views.xml • | |-- <inherited_main_model>_templates.xml • | `-- <inherited_main_model>_views.xml • `-- wizard/ • |-- <main_transient_A>.py • |-- <main_transient_A>_views.xml • |-- <main_transient_B>.py • `-- <main_transient_B>_views.xml
  • 29. Data files • Odoo is a highly data driven system. Although behavior is customized using Python code , part of a module's value is in the data it sets up when loaded. • Module data is declared via data files . • Data files have to be declared in the manifest file to be loaded, they can be declared in the 'data' list (always loaded) or in the 'demo' list (only loaded in demonstration mode). • XML files with <record> elements creates or updates a database record.
  • 30. XML files To declare a record in XML, use the record notation • Place id attribute before model. • For field declaration, name attribute is first. Then place the value either in the field tag, either in the eval attribute, and finally other attributes (widget, options, ...) ordered by importance. • The tag <data> is only used to set not-updatable data with noupdate=1. If there is only not- updatable data in the file, the noupdate=1 can be set on the <odoo> tag and do not set a <data> tag.
  • 31. • <record id="view_id" model="ir.ui.view"> • <field name="name">view.name</field> • <field name="model">object_name</field> • <field name="priority" eval="16"/> • <field name="arch" type="xml"> • <tree> • <field name="my_field_1"/> • <field name="my_field_2“ string="My Label“ widget="statusbar" statusbar_visible="draft,sent,progress,done"/> • </tree> • </field> • </record>
  • 32. Odoo supports custom tags acting as syntactic sugar: • menuitem: use it as a shortcut to declare a ir.ui.menu. • template: use it to declare a QWeb View requiring only the arch section of the view. • report: use to declare a report action. • act_window: use it if the record notation can't do what you want.
  • 33. Naming xml_id • For a menu: <model_name>_menu • For a view: <model_name>_view_<view_type>, where view_type is kanban, form, tree, search, ... • For an action: the main action respects <model_name>_action. Others are suffixed with _<detail>, where detail is a lowercase string briefly explaining the action. This is used only if multiple actions are declared for the model.
  • 34. • For a group: <model_name>_group_<group_name> where group_name is the name of the group, generally 'user', 'manager', ... • For a rule: <model_name>_rule_<concerned_group> where concerned_group is the short name of the concerned group ('user' for the 'model_name_group_user', 'public' for public user, 'company' for multi-company rules, ...).
  • 35. • <!-- views and menus --> • <record id="model_name_view_form" model="ir.ui.view"> ... • </record> • <record id="model_name_view_kanban" model="ir.ui.view"> ... • </record> • <menuitem id="model_name_menu_root" name="Main Menu" sequence="5" />
  • 36. • <menuitem id="model_name_menu_action" name="Sub Menu 1" parent="module_name.module_name_menu_root“ action="model_name_action" sequence="10" /> • <!-- actions --> • <record id="model_name_action" model="ir.actions.act_window"> ... • </record> • <record id="model_name_action_child_list" model="ir.actions.act_window"> ... • </record>
  • 37. • <!-- security --> • <record id="module_name_group_user" model="res.groups"> ... • </record> • <record id="model_name_rule_public" model="ir.rule"> ... • </record> • <record id="model_name_rule_company" model="ir.rule"> ... • </record>
  • 38. Inherited view: • The naming pattern of inherited view is <base_view>_inherit_<current_module_name>. A module may only extend a view once. Suffix the original name with _inherit_<current_module_name> where current_module_name is the technical name of the module extending the view. <record id="inherited_model_view_form_inherit_my_module" model="ir.ui.view"> ... </record>
  • 39. XML views • Basic views: Views define the way the records of a model are displayed. Each type of view represents a mode of visualization (a list of records, a graph of their aggregation, …). Views can either be requested generically via their type (e.g. a list of partners) or specifically via their id. For generic requests, the view with the correct type and the lowest priority will be used (so the lowest-priority view of each type is the default view for that type).
  • 40. Generic view declaration: • A view is declared as a record of the model ir.ui.view. • The view type is implied by the root element of the arch field • The view's content is XML thus the arch field must be declared as type="xml" to be parsed correctly.
  • 41. Tree views: • Tree views, also called list views, display records in a tabular form. • Their root element is <tree>. The simplest form of the tree view simply lists all the fields to display in the table (each field as a column): <tree string="Idea list"> <field name="name"/> <field name="inventor_id"/> </tree>
  • 42. Tree views can take supplementary attributes to further customize their behavior: • decoration-{$name} allow changing the style of a row's text based on the corresponding record's attributes. • Values are Python expressions. For each record, the expression is evaluated with the record's attributes as context values and if true, the corresponding style is applied to the row. Other context values are uid (the id of the current user) and current_date (the current date as a string of the form yyyy- MM-dd).
  • 43. • {$name} can be bf (font-weight: bold), it (font-style: italic), or any bootstrap contextual color (danger, info, muted, primary, success or warning). • Editable :Either "top" or "bottom". Makes the tree view editable in-place (rather than having to go through the form view), the value is the position where new rows appear. • Invisible.
  • 44. • <tree string="Idea Categories" decoration-info="state=='draft'" decoration-danger="state=='trashed'"> • <field name="name"/> • <field name="state“ invisible="'product_id' not in context"/>/> • </tree>
  • 45. Form views: • Forms are used to create and edit single records. • Their root element is <form>. They are composed of high-level structure elements (groups, notebooks) and interactive elements (buttons and fields):
  • 46. <form string="Idea form"> <group colspan="4"> <group colspan="2" col="2"> <separator string="General stuff" colspan="2"/> <field name="name"/> <field name="inventor_id"/> </group> <group colspan="2" col="2"> <separator string="Dates" colspan="2"/> <field name="active"/> <field name="invent_date" readonly="1"/> </group> <notebook colspan="4"> <page string="Description"> <field name="description" nolabel="1"/> </page> </notebook> <field name="state"/> </group> </form>
  • 47. Domains • In Odoo, Domains are values that encode conditions on records. A domain is a list of criteria used to select a subset of a model's records. Each criteria is a triple with a field name, an operator and a value. • By default criteria are combined with an implicit AND. The logical operators &(AND), |(OR)and!(NOT) can be used to explicitly combine criteria. They are used in prefix position (the operator is inserted before its arguments rather than between)
  • 48. Search views: • Search views customize the search field associated with the list view (and other aggregated views). Their root element is <search> and they're composed of fields defining which fields can be searched on: <search> <field name="name"/> <field name="inventor_id"/> </search>
  • 49. • Search view <field> elements can have a @filter_domain that overrides the domain generated for searching on the given field. In the given domain. • Search views can also contain <filter> elements, which act as toggles for predefined searches. • Filters must have one of the following attributes: • Domain add the given domain to the current search. • Context add some context to the current search; use the key group_by to group results on the given field name.
  • 50. <search string="Ideas"> <field name="name"/> <field name="description“ string="Name and description“ filter_domain="['|', ('name', 'ilike', self), ('description', 'ilike', self)]"/> <field name="inventor_id"/> <field name="country_id" widget="selection"/> <filter name="my_ideas" string="My Ideas“ domain="[('inventor_id', '=', uid)]"/> <group string="Group By"> <filter name="group_by_inventor" string="Inventor" context="{'group_by': 'inventor_id'}"/> </group> </search>
  • 51. Graph views • Graph views allow aggregated overview and analysis of models, their root element is <graph>. • Graph views have 4 display modes, the default mode is selected using the mandatory @type attribute taking the values: row (default)the field should be aggregated by default. Measure the field should be aggregated rather than grouped on.
  • 52. The display modes: • Bar (default)a bar chart, the first dimension is used to define groups on the horizontal axis, other dimensions define aggregated bars within each group. • By default bars are side-by-side, they can be stacked by using @stacked="True" on the <graph> • Line 2-dimensional line chart. • Pie 2-dimensional pie <graph string="Total idea score by Inventor"> <field name="inventor_id"/> <field name="score" type="measure"/> </graph>
  • 53. Calendars: • Displays records as calendar events. Their root element is <calendar> and their most common attributes are: • colorThe name of the field used for color segmentation. Colors are automatically distributed to events, but events in the same color segment (records which have the same value for their @color field) will be given the same color. • date_start record's field holding the start date/time for the event. • date_stop (optional)record's field holding the end date/time for the event
  • 54. • <!-- calendar view --> • <record model="ir.ui.view" id="session_calendar_view"> • <field name="name">session.calendar</field> <field name="model">openacademy.session</field> <field name="arch" type="xml"> • <calendar string="Session Calendar" date_start="start_date" date_stop="end_date“ color="instructor_id"> • <field name="name"/> • </calendar> • </field> • </record> …
  • 55. • <record model="ir.actions.act_window" id="session_list_action"> • <field name="name">Sessions</field> • <field name="res_model">openacademy.session</field> <field name="view_type">form</field> • <field name="view_mode">tree,form,calendar</field> </record> …
  • 56. • Kanban: • Used to organize tasks, production processes, etc… their root element is <kanban>. • A kanban view shows a set of cards possibly grouped in columns. Each card represents a record, and each column the values of an aggregation field. • Kanban views define the structure of each card as a mix of form elements (including basic HTML) and Qweb.
  • 57. <record model="ir.ui.view" id="view_openacad_session_kanban"> <fieldname="name">openacad.session.kanban</field> <field name="model">openacademy.session</field> <field name="arch" type="xml"> <kanban default_group_by="course_id"> <field name="color"/> <templates> <t t-name="kanban-box"> <div t-attf-class= "oe_kanban_color_{{kanban_getcolor(record.color. raw_value)}} oe_kanban_global_click_edit oe_semantic_html_override oe_kanban_card {{record.group_fancy==1 ? 'oe_kanban_card_fancy' : ''}}">
  • 58. <div class="oe_dropdown_kanban"> <!-- dropdown menu --> <div class="oe_dropdown_toggle"> <i class="fa fa-bars fa-lg"/> <ul class="oe_dropdown_menu"> <li> <a type="delete">Delete</a> </li> <li> <ul class="oe_kanban_colorpicker" data- field="color"/> </li> </ul> </div>
  • 59. <div class="oe_clear"> </div> </div> <div t-attf-class="oe_kanban_content"> <!-- title --> Session name: <field name="name"/> <br/> Start date: <field name="start_date"/> <br/> duration: <field name="duration"/> </div> </div> </t> </templates> </kanban> </field> </record>
  • 60. View inheritance • Instead of modifying existing views in place (by overwriting them), Odoo provides view inheritance where children "extension" views are applied on top of root views, and can add or remove content from their parent. • An extension view references its parent using the inherit_id field, and instead of a single view its arch field is composed of any number of xpath elements selecting and altering the content of their parent view.
  • 61. • Expr:An XPath expression selecting a single element in the parent view. Raises an error if it matches no element or more than one position Operation to apply to the matched element. • Inside:appends xpath's body at the end of the matched element. • Replace: replaces the matched element with the xpath's body, replacing any $0 node occurrence in the new body with the original element
  • 62. • Before:inserts the xpath's body as a sibling before the matched element. • After: inserts the xpaths's body as a sibling after the matched element. • Attributes : alters the attributes of the matched element using special attribute elements in the xpath's body.
  • 63. <!-- improved idea categories list --> • <record id="idea_category_list2" model="ir.ui.view"> • <field name="name">id.category.list2</field> <field name="model">idea.category</field> <field name="inherit_id" ref="id_category_list"/> • <field name="arch" type="xml"> <!-- find field description and add the field idea_ids after it --> • <xpath expr="//field[@name='description']" position="after"> • <field name="idea_ids" string="Number of ideas"/> • </xpath> • </field> • </record>
  • 65. Agenda - CSRF . - CSRF In Odoo - Odoo in security . - Odoo Login .
  • 66.
  • 67. What is Cross Site Request Forgery (CSRF)? Cross-site request forgery (CSRF) vulnerabilities can be used to trick a user’s browser into performing an unwanted action on your site.
  • 68. How Attack Can Happen?
  • 69. Damaged Causes By CSRF:  In Net-banking attacker can forge the request and send it to victim to steal money from Victim’s account .  Personal health information can be stolen or modified in a hospital database .  Attacker force victim to perform unwanted action which affect their profile .
  • 70.
  • 71. Mitigation Techniques: Can be mitigate by two ways * CSRF token. * Captcha.
  • 72. CSRF In Odoo: You must add this line of code in your form : `csrf_token` e.g. : <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
  • 73.
  • 74. What Is Odoo Security? It’s ability to control what user can do and what user can't-do on a different level . Have four basic operations: read, write, create, and unlink(Delete) .
  • 75. Why would I want to have field level access control in Odoo?  Restrict temporary or part-time workers from data they do not need to see.  It makes the system easier to use and the forms less cluttered.  It's important to learn all aspects of Odoo's access rights before configuring Odoo for production.
  • 76. Security mechanisms in Odoo: Groups. Access Control. Record Rules. Filed Access.
  • 77. Groups: How to assign users to groups? Security access in Odoo is configured through security groups: permissions are given to groups and then groups are assigned to users.
  • 78. Why should I use groups to restrict access rather than removing the fields? No. This is a bad idea because Odoo may have processes and other depencencies that are expecting that field to be available on the form.
  • 79. Go to Settings > Groups
  • 80. Here you can see, you can add as many as users under Users tab so that only that users can view Accounting&Finance/Billing.
  • 81. Access Control List:  In Odoo, views and menus are restricted to a user due to access right permission. Only admin has right to view all records. Access right permission is managed by creating an ir.model.access.csv file.  This file can Grant Available permissions are :  creation (perm_create).  searching and reading (perm_read).  updating existing records (perm_write).  deleting existing records (perm_unlink).  Define group to a model(optional) : – If no group: access rights applies to all users – If group: access rights applies to member of that group
  • 82.  Access controls are additive, for example if the user belongs to one group which allows writing and another which allows deleting, they can both write and delete.  Here is the steps define ir.model.access.csv file for custom model: Step 1 : Create Security folder in your custom module.  Blog/security Step 2 : Make ir.model.access.csv file in Security folder.  Blog/security/ir.model.access.csv Step3 : Edit in __manifest__.py 'data': [ 'security/ir.model.access.csv', ],
  • 83. Step4 : Write following code in your ir.model.access.csv  Defining Access Rights ( ir.model.access.csv )  id = unique identity for the permission (Example:access_blog_post_user)  name = unique name for the permission (Example:blog.post.user)  model_id/id = the model unique name of the class you want apply permission on (Example: model_blog_post)  group_id/id = Permission apply on group(Example: Blog.group_blog_user)  Where Blog:module name , group_blog_user :group id  perm_read,perm_write,perm_create,perm_unlink = the 4 values for the relative permission to read, write,create,unlink record on defined class. 1 is True and 0 is False id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink access_blog_post_user,blog.post.user,model_blog_post,Blog.group_blog_user,1,0,0,0
  • 84.
  • 85. Record Rules:  Record Rules are certain conditions that the records must satisfy for the operations such as : (read,write,delet,create) to be allowed.  it is applied , record-by-record after the access control has been applied.  Record Rules can be defined from the menu also without creating any file.  A set of permissions to which it applies (e.g. if perm_read is set, the rule will only be checked when reading a record)  A set of user groups (no group means global rule)  A domain for filtering data  If filter matches: It is accessible  If filter does not matches: It is not accessible
  • 86. Go to Settings > Security>Record Rules:
  • 87.
  • 88. Field Access An ORM field can have a groups attribute providing a list of groups.If the current user is not in one of the listed groups, he will not have access to the field: e.g:
  • 90. Dose Odoo Store Passwords in Clear text??!!  Yes by default it does, you can change this behavior if you install the module auth_crypt .  But as we all know that in term of security it is a very bad practice to store passwords without strong hashing (SHA-256+) and salting! What Odoo say about this?  Well, actually that's a feature, so that it's possible to recover lost passwords.  As for the reason for cleartext passwords: once you switch to encrypted passwords you can't recover user passwords anymore . So enabling it is a choice, because there's no going back. We don't currently plan to make passwords encrypted by default.
  • 92. Contents • What we mean by ORM in odoo? • Structural attributes. • Fields. • Method decorators. • Common ORM methods. • Domains. • Inheritance.
  • 93. What we mean by ORM in odoo? • In Odoo, the data model is described and manipulated through Python classes and objects. It is the ORM job to bridge the gap - as transparently as possible for the developer - between Python and the underlying relational database (PostgreSQL), which will provide the persistence we need for our objects. And as we know “Every thing in Odoo is an object”.
  • 94. • A key component of Odoo is the ORM layer. This layer avoids having to write most SQL by hand and provides extensibility and security services. • Business objects are declared as Python classes extending model which integrates them into the automated persistence system. • Models can be configured by setting a number of attributes at their definition. The most important attribute is _name which is required and defines the name for the model in the Odoo system. Here is a minimally complete definition of a model:
  • 95. The system will later instantiate the class once per database (on which the class' module is installed).
  • 96. Structural attributes • _name : business object name, in dot-notation (in module namespace) . • _rec_name: Alternative field to use as name, used by osv’s name_get() (default: 'name'). • _inherit: If _name is set, names of parent models to inherit from. Can be a str if inheriting from a single parent If _name is unset, name of a single model to extend in-place
  • 97. Structural attributes • _inherits : dictionary mapping the _name of the parent business objects to the names of the corresponding foreign key fields to use:
  • 98. Structural attributes • _order : Ordering field when searching without an ordering specified (default: 'id')
  • 99. Structural attributes • _auto: Whether a database table should be created (default: True) • _table: Name of the table backing the model created when _auto, automatically generated by default.
  • 100. Structural attributes • _constraints • list of (constraint_function, message, fields) defining Python constraints. The fields list is indicative Deprecated since version 8.0: use constrains().
  • 101. Structural attributes • _sql_constraints list of (name, sql_definition, message) triples defining SQL constraints to execute when generating the backing table
  • 102. Fileds • Fields are used to define what the model can store and where. Fields are defined as attributes on the model class:
  • 103. • Simple fields : fields.Char fields.Integer fields.Float fields.Date fields.Selection : When extending a model, if you want to add possible values to a selection field, you may use the selection_add keyword : fields.Text fields.Boolean fields.Monetary fields.Html: Used to store HTML, provides an HTML widget.
  • 104. • Reserved fields: Odoo creates a few fields in all models. These fields are managed by the system and shouldn't be written to. They can be read if useful or necessary:  id (Id)The unique identifier for a record in its model.  create_date (Datetime)Creation date of the record.  create_uid (Many2one)User who created the record.  write_date (Datetime)Last modification date of the record.  write_uid (Many2one)user who last modified the record.  This information is available from the web client, navigating to the Developer Mode menu and selecting the View Metadata option.
  • 105. • Computed Fields :  Fields can be computed (instead of read straight from the database) using the compute parameter. It must assign the computed value to the field. If it uses the values of other fields, it should specify those fields using depends() :
  • 106.  computed fields are not stored by default, they are computed and returned when requested. Setting store=True will store them in the database and automatically enable searching. The decorator odoo.api.depends() must be applied on the compute method to specify the field dependencies
  • 107. to allow setting values on a computed field, use the inverse parameter. It is the name of a function reversing the computation and setting the relevant fields.  multiple fields can be computed at the same time by the same method, just use the same method on all fields and set all of them :
  • 108. • The computed field can be read, but it can't be searched or written. To enable these operations, we first need to implement specialized functions for them. Along with the compute function, we can also set a search function, implementing the search logic, and the inverse function, implementing the write logic.
  • 109. • Related fields : A special case of computed fields are related (proxy) fields, which provide the value of a sub-field on the current record. They are defined by setting the related parameter and like regular computed fields they can be stored. • Behind the scenes, related fields are just computed fields that conveniently implement search and inverse methods. This means that we can search and write on them out of the box, without having to write any additional code.
  • 110. • onchange: updating UI on the fly : • When a user changes a field's value in a form (but hasn't saved the form yet), it can be useful to automatically update other fields based on that value e.g. updating a final total when the tax is changed or a new invoice line is added.
  • 111. • computed fields are automatically checked and recomputed, they do not need an onchange • for non-computed fields, the onchange() decorator is used to provide new field values
  • 112. • Common attributes : There are many attributes may be provided when instantiating a field as a common attributes : String : the label of the field seen by users (string); if not set, the ORM takes the field name in the class (capitalized). Help: the tooltip of the field seen by users (string) Readonly: whether the field is readonly (boolean, by default False) Required: whether the value of the field is required (boolean, by default False) Index: whether the field is indexed in database (boolean, by default False) Common fields attributes
  • 113. default : the default value for the field; this is either a static value, or a function taking a recordset and returning a value; use default=None to discard default values for the field. states : a dictionary mapping state values to lists of UI attribute-value pairs; possible attributes are: 'readonly', 'required', 'invisible'. Note: Any state-based condition requires the state field value to be available on the client-side UI. This is typically done by including it in the relevant views, possibly made invisible if not relevant for the end-user.
  • 114. groups : comma-separated list of group xml ids (string); this restricts the field access to the users of the given groups only copy (bool) : whether the field value should be copied when the record is duplicated (default: True for normal fields, False for one2many and computed fields, including property fields and related fields) oldname (string): the previous name of this field, so that ORM can rename it automatically at migration Translate(bool) : In case of True it means can be translated size (int): the maximum size of values stored for that field
  • 115. • Relational fields : 1. Many2one : The many2one relationship accepts two positional arguments: the related model (corresponding to the comodel keyword argument) and the title string. It creates a field in the database table with a foreign key to the related table. Parameters : • comodel_name : name of the target model (string) ‘mandotary’ • domain : an optional domain to set on candidate values on the client side (domain or string) • context : an optional context to use on the client side when handling that field (dictionary) • ondelete : what to do when the referred record is deleted; possible values are: 'set null', 'restrict', 'cascade' • auto_join : whether JOINs are generated upon search through that field (boolean, by default False) • delegate : set it to True to make fields of the target model accessible from the current model (corresponds to _inherits)
  • 116. 2. One2many : An inverse of many2one can be added to the other end of the relationship. This has no impact on the actual database structure, but allows us easily browse from the one side of the many related records. A typical use case is the relationship between a document header and its lines. One2many makes it easy for a parent to keep track of its children. • Parameters : comodel_name : name of the target model (string) inverse_name : name of the inverse Many2one field in comodel_name (string) domain : an optional domain to set on candidate values on the client side (domain or string) context : an optional context to use on the client side when handling that field (dictionary) auto_join : whether JOINs are generated upon search through that field (boolean, by default False) limit : optional limit to use upon read (integer) (Comodel_name + inverse_name ) are mandatory fields.
  • 117. 3.Many2many : At the database level, it does not add any columns to the existing tables. Instead, it automatically creates a new relationship table that has only two ID fields with the foreign keys for the related tables. The relationship table name and the field names are automatically generated. The relationship table name is the two table names joined with an underscore with _rel appended to it. Parameters • comodel_name : name of the target model (string) ‘mandatory’ • Parameters • relation : optional name of the table that stores the relation in the database (string) • column1 : optional name of the column referring to "these" records in the table relation (string) • column2 : optional name of the column referring to "those" records in the table relation (string) • domain : an optional domain to set on candidate values on the client side (domain or string) • context : an optional context to use on the client side when handling that field (dictionary) • limit : optional limit to use upon read (integer)
  • 118. Method decorators • Before we go to decorators we need first to know little things about recordest • Recordset : New in version 8.0 , Interaction with models and records is performed through recordsets, a sorted set of records of the same model. Methods defined on a model are executed on a recordset, and their self is a recordset
  • 119. • Record cache and prefetching : Odoo maintains a cache for the fields of the records, so that not every field access issues a database request, which would be terrible for performance. The following example queries the database only for the first statement: To avoid reading one field on one record at a time, Odoo prefetches records and fields following some heuristics to get good performance. Once a field must be read on a given record, the ORM actually reads that field on a larger recordset, and stores the returned values in cache for later use. The prefetched recordset is usually the recordset from which the record comes by iteration. Moreover, all simple stored fields (boolean, integer, float, char, text, date, datetime, selection, many2one) are fetched altogether; they correspond to the columns of the model's table, and are fetched efficiently in the same query.
  • 120. Method decorators • decorators are important for the server to know how to handle the method. • There are two different API styles, namely the "traditional" and "record" styles. • In the "traditional" style, parameters like the database cursor, user id, context dictionary and record ids (usually denoted as cr, uid, context, ids) are passed explicitly to all methods. In the "record" style, those parameters are hidden into model instances, which gives it a more object- oriented feel. • A decorator is a function that takes a function as input and returns a function. • The anatomy of the decorator is: @decorator-expression • Decorator-expression is an expression that returns a callable thing. The callable thing has to take a single argument. Function definition is a function definition (it, therefore, must begin with def). • In older version of odoo, we use a cursor, uid, context and ids for defining all method. • In odoo 9, odoo 10 we use self as the parameter when defining a method with certain method decorators.This decorator are passed the parameters explicitly to the method. Which provide a smooth way to write functions and avoid complications.
  • 121. • 1.@api.one: It is specific for one record and cannot be used for multiple records. Self is redefined as current record. Example @api.one def get_product(self): self.product_name = ‘desktop’ This function will automatically write product name field of each record with ‘desktop’.
  • 122. • 2.@api.multi: It can use for multiple records, so we can loop through it. Here Self-contains recordset so that we need for loop for iterating through each record. Example @api.multi def get_product(self): For the record in self: self.product_name = ‘desktop’
  • 123. • 3.@api.model: This decorator will convert old API calls to decorated function to new API signature. • 4.@api.depends: This decorator is specifically used for computing fields in odoo. The decorator function works only if any of the fields specified in the @api.depends is changed in the form. Dependencies can be dotted paths when using sub-fields. Example: @api.depends(‘partner_id.street’) def _get_street(self): for record in self: for line in record.partner_id: record.street = line.street Computed field are not stored by default, they have computed the function and return the value.We use store = True to store the computed value to the database.
  • 124. • 5.@api.onchange: This decorator will avoid the on change attribute in the xml file. The fields are written as the parameter of the function. Example: @api.onchange(‘date_of_birth’,’age’) def onchange_age_calculation(self ): if not self.date_of_birth: self.age = 0 else: today_date = datetime.now().year date_split = self.date_of_birth.split(‘-‘,1) birth_year = date_split[0] self.age = today_date -int(birth_year) This function will automatically write age field when changing the value of date_of_birth field in form view.
  • 125. • 6.@api.constrains: This decorator will ensure that decorated function will be called on creating, write, unlink operation. It will act as a constraint checker. This will especially use for warning messages and validation.
  • 126. Common ORM methods • search() : Takes a search domain, returns a recordset of matching records: • create() : Takes a number of field values, and returns a recordset containing the record created
  • 127. • write()Takes a number of field values, writes them to all the records in its recordset. Does not return anything: • browse()Takes a database id or a list of ids and returns a recordset:
  • 128. • ensure_one() checks that the recordset is a singleton (only a single record), raises an error otherwise:
  • 129. Domains • A domain is a list of criteria, each criterion being a triple (either a list or a tuple) of (field_name, operator, value) where: • field_name (str) : a field name of the current model, or a relationship traversal through a Many2one using dot-notation e.g. 'street' or 'partner_id.country'operator (str)an operator used to compare the field_name with the value.
  • 130. • operator (str) : an operator used to compare the field_name with the value. Valid operators are: 1. =equals to 2. !=not equals to 3. > greater than 4. >= greater than or equal to 5. <less than 6. <=less than or equal to 7. =?unset or equals to (returns true if value is either None or False, otherwise behaves like =) 8. =like : matches field_name against the value pattern. An underscore _ in the pattern stands for (matches) any single character; a percent sign % matches any string of zero or more characters. 9. Like matches field_name against the %value% pattern. Similar to =like but wraps value with '%' before matching 10. not like doesn't match against the %value% pattern 11. Ilike case insensitive like 12. not ilike case insensitive not like 13. =ilike case insensitive =like 14. In is equal to any of the items from value, value should be a list of items 15. not in is unequal to all of the items from value 16. child_of is a child (descendant) of a value record. 17. Takes the semantics of the model into account (i.e following the relationship field named by _parent_name).
  • 131. • Value variable type, must be comparable (through operator) to the named field • Domain criteria can be combined using logical operators in prefix form: • & : logical AND, default operation to combine criteria following one another. Arity 2 (uses the next 2 criteria or combinations). • | : logical OR. • ! : logical NOT.
  • 132. Inheritance • Odoo provides three different mechanisms to extend models in a modular way:  Classical inheritance : When use (_inherit + _name) = the new model will use the existing model  Extension inheritance : When use (_inherit) without (_name) in new model it will replace the existing one  Delegation inheritance : The third inheritance mechanism provides more flexibility (it can be altered at runtime) but less power: using the _inherits a model delegates the lookup of any field not found on the current model to "children" models. The delegation is performed via Reference fields automatically set up on the parent model.(in this type only fields are inherited)
  • 136.
  • 137. Done By: Zaineb Alnzeer Esra Adil Amel Salah Rawan Mohiealdeen NCTR Company. E-Service Department.