blog image

in this setup we will collect all the  basic concept or mostly used information related to odoo .

Database:

http://localhost:8069/web/database/manager

This url i s used for manage database in odoo.you can delete,make new one,duplicate from the existing database and other stuff .

 

Login:

http://localhost:8069/web/login

if you want to login with debug mood enable then you can hit below url in your browser.

http://localhost:8069/web?debug=assets

 

Setup the email in odoo 

To seup the icoming and outgoing mail server in odoo application follow below path:

1.Go to settings section

2.On the top navbar you will see Technical, click on this

3.Then , in Email section you will see incoming mail server and outgoing mail server

4.Click on outgoing mail server

    4.1: create new outgoing mail server 

           you can give any name you want,select  TLS (STARTTLS) or SSL/TLS (with post-465),set smtp server as smtp.gmail.com and               port as 587 then you can  seup email and password.

 

 

Instead of updating modules you can write update while running project like

./bin/odoo start -u module_name -d database_name

 

widget used in my project:

   <field name="country_id"  widget='many2onebutton'/>
   <field name="country_ids"  widget='many2many_tags'/>
  <field name="country_id" options="{'no_open':True,'no_create':True}" />
      <tree  name='adacemic_info_tree_view' editable='top'>
<tree  name='adacemic_info_tree_view'  editable="buttom" widget="section_and_note_one2many">
           <field name="sequence" widget='handle'/>






#for models
    track_visibility='onchange' or 'always'

 

 

btn in odoo

1.object btn-- when we clikc python function is excuted

2.text btn - when click new view or xml file is open

 

 

 

 

Different attributes of fields in odoo

1.readonly="1" or readonly="True"

2.invisible="1"

3.editable="1"

4.required="1"

5.default="hello world"

6.string="Name"

7.help="write help wod"

 

 

Domain and context in odoo

if in any object we do perform filtering , we do through  domain.

for example we filter data whose gender is only male:

    <record id="school_staff_action" model="ir.actions.act_window">
        <field name="name">Staff</field>
        <field name="res_model">school.staff</field>
        <field name="view_mode">tree,form,search,kanban</field>

        <field name="domain">[('gender','=','male')]</field>


        <field name-'context'> {'default_gender':'male',
                                'search_default_male':1 } </field>
 
    </record>

 

Note: when you change on action ,you need to change on view as well.

settings>Technical.Actions>search through your action name> delete action > upgrade model.

 

Constrains API for form validations

mailny there are three type of error in odoo

1.UserError

2.ValidationError

3.AccessError

from odoo import models,fields,api,_
from odoo.exceptions import ValidationError,UserError

#to show any error or warning we need to use api so we import above



   @api.constrains('age')
    def _validate_age(self):
        for record in self:
            if record.age<=18:
                raise ValidationError(_('Age Must be greater than 18'))

 

 

@api.depends nad compute attribute in odoo

    hand_salary=fields.Float(string='In hand Salary')
    epf_esi=fields.Float(string='EPF+ESI')
    ctc_salary=fields.Float(string='CTC',
        compute='_compute_ctc' )
    
    @api.depends('hand_salary','epf_esi')
    def _compute_ctc(self):
        for record in self:
            ctc=0
            if record.hand_salary:
                ctc=ctc+record.hand_salary
            if record.epf_esi:
                ctc=ctc+record.epf_esi
            record.ctc_salary = ctc

 

 

ORM Methods in Odoo

1.search (all)

2.search_count 

3.browse (retrive or list)

4.ref (take id from previous views)

5.create (save)

6.write (updtae)

7.copy (duplicate)

8.unlink (delete)

 

    #Odoo ORM 
    def check_orm(self):
        # 1.search
        print('\nORM::: search')
        search_var=self.env['school.staff'].search(['|',('gender','=','female'), 
                                       ('status','=','active')])
        '''
        if you want to search data on multiple condition by default odoo
        perform and operation, if you need to perform or operation you need
        to mention by adding '|' at the very first argument in search function
        '''
        print(search_var)
        # for rec in search_var:
        #     print(rec.name)
        
        # 2.search_count
        print('\nORM::: search_count')
        search_var_count=self.env['school.staff'].search_count([('gender','=','female')]) 
        print(search_var_count)
        
        # 3.browse
        print('\nORM::: browse')
        # for single retrive 
        browse_orm=self.env['school.staff'].browse(1)
        #if you want multiple record you need to list id in list 
        # browse_orm=self.env['school.staff'].browse([1,2,3]) 
        '''
        to get all information you need to loop data
        '''
        print(browse_orm.name)
        
        # 4.ref
        print('\nORM::: ref')
        '''
        suppose you make a record through xml, to get id of that record or to get the 
        external_id
        '''
        odoo_ref=self.env.ref('school.school_staff_view_form')
        print(odoo_ref)
        print(odoo_ref.id) # to get  browser id
        print(odoo_ref.name)
        print(odoo_ref.type)
        print(odoo_ref.model_data_id)
        
        # 5.create
        print('\nORM::: create')
                      create_new_record=self.env['school.staff'].create({"name":"testing","email":"testing@gmail.com"})
        print(create_new_record)
        print('New record created successfully....')
        
        # 6.write
        print('\nORM::: write')
        browse_id=self.env['school.staff'].browse(10)
        browse_id.write({"name":"updated name","email":"updated 
                 email","age":20,"gender":"female"})
        print(browse_id)
        print("Updated successfully")
        
        # 7.copy
        print('\nORM::: copy')
        duplicated_browse_id=self.env['school.staff'].browse(1)
        new_duplicated_record=duplicated_browse_id.copy()
        print(new_duplicated_record)
        print("duplicated successfully....")
        
        # 8.link
        print('\nORM::: link')
        delete_browse_id=self.env['school.staff'].browse(6)
        deleted_record=delete_browse_id.unlink()
        print(deleted_record)
        print("deleted  successfully....")

 

 

Create and write Method override in odoo

    #create method override
    @api.model
    def create(self,vals):
        print("Calling while creating new record....")
        res=super(SchoolStaff,self).create(vals)
        print(self) # return object
        print(vals) #return incoming data in dictionary form
        print(res) # return object with id
        if vals.get('gender')=='male':
            res['name']='Mr '+res['name']
        if vals.get('gender')=='female':
            res['name']='Ms '+res['name']
        return res
 
    
    # override write method  
    # @api.multi
    def write(self,vals):
        print("Calling while updating record...")
        #note in vals only the record which have value is comes under vals dictionary
        res=super(SchoolStaff,self).write(vals)
        print(self)
        print(vals)
        print(res)
        return res

 

How to make one2many field required in odoo

 

You can write in create and write method also too. according to requirements

    #create method override
    @api.model
    def create(self,vals):
       
        
        #how to make One2many field required,note at least one field of One2many Model has 
        required=True
        if not vals.get('staff_academic_info_ids'):
            raise ValidationError(_("Staff Academic Qualification is Required.."))


  #check by making one of the one2many model field required=True whether it will work or not with out external validation or not

 

 

How to Create action (to call view) buttom in odoo

    <button string="Go To CRM" name="%(crm.crm_lead_action_pipeline)d" type="action" class="oe_highlight"/>

to get the action  name: enable debugging mode>> click on Edit Action >> copy the External ID

 

super call unlink() method (check any condition before deleting record)

    #super call unlink method before deleting any record
    # @api.multi
    def unlink(self):
        for rec in self:
            if rec.status=="active":
                raise ValidationError(_("Recored Cannot be deleted, if it's Status is active"))
        return super(SchoolStaff,self).unlink()

 

 

how to create wizard in odoo

wizard is like a pop up window to perform  particular function.

to create wizard in odoo addons follow mntion ways:

1.create wizard folder in addons root directory

2.create __init__.py file ,one python file and one_xml file (create according to requirements)

 

How to perform CRUD operation in wizard 

    def update_info_func(self):
        active_id = self.env.context.get('active_id')
        active_model = self.env.context.get('active_model')
        student = self.env['school.student'].sudo().browse(active_id) #browsable id with object
        country_list=[]
        student.subject_ids=[[(5,0,0)]] # to empty one2many field 
        for vals in self.country_ids:
            country_list.append(vals)
        subjects=[]
        for vals in self.subject_ids:
            subjects.append(0,0,{
                "name":vals.name,
                "student_id":vals.student_id.id # here student_id is one2many field ma many2one field ko ho hai
            })
        vals={
            "full_name":self.full_name,
            "age":self.age,
            "country_id":self.country_id.id, # for many2one
            "country_ids":[(6,0,country_list)], # for many2many
            "subjects_ids":subjects
        }
        student.write(vals)

 

How to pervent wizard from disappearing

    def update_info_func(self):
        active_id = self.env.context.get('active_id')
        ::
        ::
  
        student.write(vals)
        return {
               "type":"ir.actions.donothing"

               }

 

How to call wizard from menu

<menuitem action="module_name.wizard_id_name"/>

 

how to call python function by menu or server actions

we have basic actions to call view through ir.action,act_window but, if we want to call menu or actions through python function then we use server actions.

 

 

how to get default_get() value in wizard from current records.

    @api.model
    def default_get(self, fields):
        active_id = self.env.context.get('active_id')
        active_model = self.env.context.get('active_model')
        res = super(ModelName, self).default_get(fields)
        brw_id = self.env['school.student'].sudo().browse(int(active_id))
        if not active_model == 'school.student' or not active_id:
            raise UserError(_('You cannot proceed with wrong data!'))
        lst=[]
        for rec in self.brw_id.country_ids:
            lst.append(rec.id)
        lst2=[]
        for rec in self.subject_ids:
            lst2.append(
                (0,0,{"name":rec.name,"mark":rec.mark,'school_id':rec.school_id.id})
                        )
        if active_id:
            res['full_name']='rajesh hamal'
            res['deapartment_id']=brw_id.deapartment_id.id # from many2one
            res['country_ids']=[(6,0,lst)],  #for many2many
            res['subjects_ids']=lst2,  # for one2many

        return res

 

 

How to create new record from wizard

    def create_student(self):
        lst=[]
        for rec in self.brw_id.country_ids:
            lst.append(rec.id)
        lst2=[]
        for rec in self.subject_ids:
            lst2.append(
                (0,0,{"name":rec.name,"mark":rec.mark,'school_id':rec.school_id.id})
                        )
        student_id=self.env['school.student'].create(
            {
                "full_name":self.full_name,
                'age':self.age,
                "department_id":self.department_id.id, # for many2one
                "country_ids":[(6,0,lst)], # for many2many
                "subjects_ids":lst2 # for one2many
            }
        )
        # or you can create one2many records like this also
        """
        for rec in self.subjects_ids:    
            self.env['school.subjects'].create(
                {
                    "name":rec.name,
                    "mark":rec.mark,
                    "student_id":student_id.id
                }
            )
        """
        context=dict(self.env.context)
        context['form_view_initial_mode']='edit'
        return {
            "name":_("created student"),
            "context":context,
            "view_type":'form',
            "res_model":'school.student',
            "rest_id":student_id.id,
            "type":'ir.actions.act_window"
        }

 

 

onchnage and compute funaction

onchange:it work on only current value only

compute: it works on all records, old records as well

 

show only particular status in statusbar

<fields name='status' widget='statusbar' statusbarvisible='active,rejoin'/>

 

 

 ref

suppose you make a record through xml , to get the id of that record or to get the external_id 

search_var=self.env.ref('school.student_form_view_id').id   here .id is to get browse id
print(search_var)
print(search_var.id)
print(search_var.model_data_id)
print(search_var.name)
print(search_var.type)

 


About author

author image

Amrit Panta

Python developer, content writer



3 Comments

Amanda Martines 5 days ago

Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.

Reply

Baltej Singh 5 days ago

Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Marie Johnson 5 days ago

Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Leave a Reply

Scroll to Top