create dictionary using python- odoo


Example -1
a = [1,2,3,4,5]
result = {}
for item in a:
    result.setdefault(item,{}).update({'name':'name','age':'30'})
print(result)

Example -2
a = [
["1", "ananthu","30"],
["2", "arun","30"],
["3", "shyju","30"],
["4", "sreekanth","30"],
["5", "nishar","30"],
]

items = {}
for id, name,age in a:
    id_dict = items.setdefault(id, {})
    id_dict.update({'name':name,'age':age})
print(items)
output
{'1': {'name': 'ananthu', 'age': '30'}, '5': {'name': 'nishar', 'age': '30'}, '2': {'name': 'arun', 'age': '30'}, '4': {'name': 'sreekanth', 'age': '30'}, '3': {'name': 'shyju', 'age': '30'}}
Advertisements

odoo tree view default group by using filed


<record id="action_project_milestone_invoicing_view" model="ir.actions.act_window">
<fieldname="type">ir.actions.act_window</field>
<fieldname="name">Project Milestone Invoicing</field>
<fieldname="res_model">project.milestone.invoicing</field>
<fieldname="view_mode">tree,form</field>
<fieldname="context">{'group_by':['project']}</field>
<fieldname="view_type">form</field>
<fieldname="help"type="html">
<pclass="oe_view_nocontent_create">Create the first Project with Milestone</p>
</field>
</record>

[/code ]

CREATING TREE VIEW REPORT USING SQL QUERY-odoo


1). Create a custom model,
2). Create a Tree View,
3). Create a menu entry.

Create a custom model

class ProjectMilestoneInvoicing(models.Model):
    _name = "project.milestone.invoicing"
    _auto = False

    project = fields.Many2one('project.project')
    client = fields.Many2one('res.partner')
    milestone = fields.Char(string='Milestone')
    payment = fields.Float(string='Payment')

    @api.model_cr
    def init(self):
        print "Connected"
        tools.drop_view_if_exists(self._cr, 'project_milestone_invoicing')
        self._cr.execute("""
            CREATE OR REPLACE VIEW project_milestone_invoicing AS (
                SELECT 
                row_number() OVER () as id,
                ps.project_id as project,
                ps.milestone as milestone,
                ps.payment as payment, 
                aa.partner_id as client 
                FROM public.project_stages ps 
                LEFT JOIN  project_project pp ON ps.project_id = pp.id
                LEFT JOIN  account_analytic_account aa ON pp.analytic_account_id = aa.id
                where  ps.milestone is not null and ps.project_id is not null
            )""")

Create a View

<!-- Form view Action for Project Milestone Invoicing -->
        <record id="action_project_milestone_invoicing_view" model="ir.actions.act_window">
            <field name="type">ir.actions.act_window</field>
            <field name="name">Project Milestone Invoicing</field>
            <field name="res_model">project.milestone.invoicing</field>
            <field name="view_mode">tree,form</field>
            <field name="view_type">form</field>
            <field name="help" type="html">
                <p class="oe_view_nocontent_create">Create the first milestone</p>
            </field>
        </record>

        <record model="ir.ui.view" id="action_project_milestone_invoicing_tree">
            <field name="name">Project Milestone Invoicing</field>
            <field name="model">project.milestone.invoicing</field>
            <field name="arch" type="xml">
                <tree string="Project Milestone Invoicing" create="false">
                    <field name='project'/>
                    <field name='client' />
                    <field name='milestone' />
                    <field name='payment' />
                </tree>
            </field>
        </record>

Create Menu

<!-- Menu item for Project Milestone Invoicing-->
        <menuitem name="Project Milestone Invoicing" action="action_project_milestone_invoicing_view" id="menu_project_milestone_invoicing_act" parent="project.menu_project_config" sequence="4"/>

How to update Many2many field


@api.model
    def create(self,vals):
        project_ids = []
        stage_obj = self.env['project.task.type']
        result = super(Project, self).create(vals)
        for resource in result:
            for source in resource.stage_ids:
                if source:
                    stage_id = stage_obj.search([('id', '=',source.name.id)])
                    project_ids.append(result.id)
                    stage_id.update({'project_ids': [( 6, 0, project_ids)]})
        return result

or
@api.model
    def create(self, vals):
        stage_obj = self.env['project.task.type']
        result = super(Project, self).create(vals)
        for resource in result.stage_ids:
            stage_id = stage_obj.search([('id', '=',resource.name.id)])
            if stage_id:
                stage_id.write({'project_ids': [( 4, result.id)]})
        return result

#stage_id_s.write({'project_ids': [( 3, self.id)]}) (unlink)
#stage_id.write({'project_ids': [( 4, result.id)]}) (create new)

How to add button in tree view header near “Create” and “Import” buttons Odoo10


1). I create some js script (tree_menu/static/src/js/tree_view_button.js) with click listener for my button :

odoo.define('tree_menu.tree_view_button', function (require){
"use strict";


var core = require('web.core');
var ListView = require('web.ListView');
var QWeb = core.qweb;


ListView.include({       
    
        render_buttons: function($node) {
                var self = this;
                this._super($node);
                    this.$buttons.find('.o_list_tender_button_create').click(this.proxy('tree_view_action'));
        },

        tree_view_action: function () {           
                
        this.do_action({               
                type: "ir.actions.act_window",               
                name: "product",               
                res_model: "product.template",               
                views: [[false,'form']],               
                target: 'current',               
                view_type : 'form',               
                view_mode : 'form',               
                flags: {'form': {'action_buttons': true, 'options': {'mode': 'edit'}}}
        });
        return { 'type': 'ir.actions.client','tag': 'reload', } } 

});

});

2). After that, create tree_menu/static/src/xml/tree_view_button.xml with the template, which replaces “Create” button if I use project.project model

<?xml version="1.0" encoding="UTF-8"?>
      <template id="template" xml:space="preserve">       
          <t t-extend="ListView.buttons">                   
            <t t-jquery="button.o_list_button_add" t-operation="replace">                           
                  <button t-if="widget.model == 'purchase.order'" class="btn btn-primary btn-sm o_list_tender_button_create" type="button">Create Tender</button>
                  <button t-if="widget.model != 'purchase.order'" class="btn btn-primary btn-sm o_list_button_add" type="button">Create</button>
            </t>       
          </t>   
      </template>

3). After that, add js script in web.asset_backend (Create file tree_menu/views/tree_view_asset.xml)

<?xml version="1.0" encoding="utf-8"?>   
<odoo>       
      <data>           
            <template id="assets_backend" name="tree view menu" inherit_id="web.assets_backend">               
                  <xpath expr="." position="inside">                   
                        <script type="text/javascript" src="/tree_menu/static/src/js/tree_view_button.js"></script>               
                  </xpath>           
            </template>       
      </data>   
</odoo>

4). And finally, add in __manifest__.py section ‘qweb’ for ‘qweb’: [‘static/src/xml/tree_view_button.xml’], and place file views/project.xml in ‘data’ section.

{
    'name': 'odoo10 Tree View JS Menu',
    'version': '1.0',
    'category': 'General',
    'summary': 'odoo10 Tree View JS Menu',
    'description': """ odoo10 Tree View JS Menu """,
    'author': 'Ananthu',
    'website': 'http://www.codersfort.com',
    'depends': ['base','purchase','web'],
    'data':[
            'views/tree_view_asset.xml',
            ],
    'qweb': ['static/src/xml/tree_view_button.xml'],       
    'demo': [],
    'installable': True,
    'application': True,
    'auto_install': False,
}

How to add custom font to qweb report


1). Create font folder under “module_name/static/src/fonts/”


2). create .css file (ref :https://css-tricks.com/snippets/css/using-font-face/)


@font-face {
    font-family: 'calibri';
    src: url('../fonts/Calibri.eot'); /* IE9 Compat Modes */
    src: url('../fonts/Calibri.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('../fonts/Calibri.woff2') format('woff2'), /* Super Modern Browsers */
         url('../fonts/Calibri.woff') format('woff'), /* Pretty Modern Browsers */
         url('../fonts/Calibri.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('../fonts/Calibri.svg#Calibri') format('svg'); /* Legacy iOS */
}
.footer_text
{
    font:normal 12px calibri !important;
    text-align: center !important;
    color: #000000 !important;
    padding-top: 5px !important;
}

3). Add your new style sheet

<?xml version="1.0" encoding="UTF-8"?>
<openerp>
    <data>
    <template inherit_id="report.minimal_layout" id="minimal_layout_inherit">
      <xpath expr="//head" position="inside">
             <link rel='stylesheet' href="/feag_header_footer/static/src/css/feag_layout_style.css"/>
             <link rel='stylesheet' href="/feag_header_footer/static/src/css/feag_report_style.css"/>
      </xpath>
    </template>
    </data>
</openerp>

4). now you can use the class in HTML tags. eg.

How to create record adding one2many values in odoo


class sale_order(models.Model):
    _inherit = "sale.order"
    
    #By default load the terms and conditions configured in the master T&C configuration
    @api.model
    def default_get(self,vals):
        terms = []
        terms_obj = self.env['so.terms.config']
        termsids = terms_obj.search([])
        for rec in termsids:
            terms.append((0, 0, {'name':rec.name,'description' : rec.description}))
        res = super(sale_order, self).default_get(vals)      
        res.update({'terms': terms})
        return res

    terms = fields.One2many('sale.order.terms.conditions','order_id',string='Terms &amp; Conditions',copy=True)

How to create sequence Code in odoo


.py file

class res_partner(osv.osv):
    _inherit = 'res.partner'
    _description = "Customers"

    _columns = {
        'code': fields.char('Student ID',size=64, readonly=True),
    }
    
    _sql_constraints = [
    ('unique_code', 'unique(code)', 'Number of Student must be unique!'), 
    ]  
    
    # Override the customer create fuction for genarate Students Unique number 
    def create(self, cr, uid, vals, context=None):
        if vals.get('is_company') == True:
                vals['code']=self.pool.get('ir.sequence').get(cr, uid, 'res.partner.student')
        return super(res_partner,self).create(cr, uid, vals, context)   

.xml file

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data noupdate="1">

    <!-- Sequence types for customer codes -->

    <record id="seq_type_res_student" model="ir.sequence.type">
        <field name="name">Student Code</field>
        <field name="code">res.partner.student</field>
    </record>

    <!-- Sequences for customer codes -->

    <record id="seq_res_student" model="ir.sequence">
        <field name="name">Student Code</field>
        <field name="code">res.partner.student</field>
        <field name="prefix"></field>
        <field name="padding">3</field>
    </record>
      
    </data>
</openerp>