Odoo Wizard writes to model but getting values from models doesn`t doesnt populate the wizard fields - odoo

I have a wizard below that writes to the database but doesnt read the values written to the database and display in the view.
I using the get_opinion to read the opinions and the get_notes to read the notes , but when i click on the buttons they just disappear with no error , where am i going wrong
Q2 , in this code which is part of the code below why am i getting model_name none
if context is None: context = {}
model_name=context.get('active_model')
print model_name #gives NONE why ?
Q3 How can i list all fields in context?
The module code is as below
class opinion(models.TransientModel):
_name='opinion'
opinion_emission = fields.Text(string='OPINION EMISSION')
notes = fields.Text(string='Additional Notes')
defaults={
'opinion_emission': lambda self : self.get_opinion(self),
'notes': lambda self : self.get_notes(self),
}
def save_it(self, cr, uid,ids , context=None):
# context = dict(self._context or {} )
if context is None: context = {}
active_id = context.get('active_id',False)
print 'active_id' , active_id
if active_id :
# op = self.env['opinion'].browse(active_id)
info = self.browse(cr,uid,ids)
self.pool.get('opinion').write(cr,uid,context['active_id'],{'opinion_emission': info[0].opinion_emission,'notes': info[0].notes})
return {
'type': 'ir.actions.act_window_close',
}
#functions that get the info stored in db
#api.one
def get_opinion(self):
ids=self._ids
cr = self._cr
uid = self._uid
context = self._context
if context is None: context = {}
active_id = context.get('active_id',False)
print 'active_id' , active_id
if active_id :
return self.env['opinion'].browse(cr, uid, context['active_id'], context).opinion_emission
#api.one
def get_notes(self,records=None):
ids=self._ids
cr = self._cr
uid = self._uid
context = self._context
if context is None: context = {}
model_name=context.get('active_model')
print model_name #gives NONE why ?
active_id = context.get('active_id',False)
print 'active_id' , active_id
if active_id :
print 'output',self.env['opinion'].browse(cr, uid, context['active_id'], context)[0].notes
return self.env['opinion'].browse(cr, uid, context['active_id'], context)[0].notes
The xml view code is :
<openerp>
<data>
<record id="view_opinion_wizard" model="ir.ui.view">
<field name="name">opinion_wizard.form</field>
<field name="model">opinion</field>
<field name="type">form</field>
<field name="arch" type="xml">
<!-- create a normal form view, with the fields you've created on your python file -->
<form string="OPINION" version="8.0">
<button icon="gtk-ok" name="get_notes" string='SET VAL' type="object" />
<group >
<separator string="Please insert OPINION" colspan="2"/>
<field name="opinion_emission" string="OPINION EMISSION "/>
<field name="notes" string="NOTES"/>
<newline/>
</group>
<div style="text-align:right">
<button icon="gtk-cancel" special="cancel" string="Cancel"/>
<button icon="gtk-ok" name="save_it" string="SAVE INFO" type="object" />
<button icon="gtk-ok" name="get_notes" string="GET NOTES" type="object" />
<button icon="gtk-ok" name="get_opinion" string="GET OPINION" type="object" />
</div>
</form>
</field>
</record>
<!-- your action window refers to the view_id you've just created -->
<record id="action_opinion" model="ir.actions.act_window">
<field name="name">OPINION</field>
<field name="type">ir.actions.act_window</field>
<field name="res_model">opinion</field>
<field name="view_type">form</field>
<field name="view_mode">form</field>
<field name="view_id" ref="view_opinion_wizard"/>
<field name="target">new</field>
</record>
<menuitem name="OPINION" id="menu_opinion" action="action_opinion" parent="timeorder_ratecard_rnd_menu"/>
</data>

This is new API code try this code:
class opinion(models.TransientModel):
_name = 'opinion'
opinion_emission = fields.Text(default=lambda self: self.get_opinion(self), string='OPINION EMISSION')
notes = fields.Text(default=lambda self: self.get_notes(self), string='Additional Notes')
#api.multi
def save_it(self):
active_id = self.env.context.get('active_id', False)
print 'active_id', active_id
if active_id:
op = self.env['opinion'].browse(active_id)
op.write({'opinion_emission': self.opinion_emission, 'notes': self.notes})
return {'type': 'ir.actions.act_window_close', }
#functions that get the info stored in db
#api.one
def get_opinion(self):
active_id = self.env.context.get('active_id', False)
print 'active_id', active_id
if active_id:
return self.env['opinion'].browse(active_id).opinion_emission
#api.one
def get_notes(self, records=None):
model_name = self.env.context.get('active_model')
print model_name # gives NONE why ?
active_id = self.env.context.get('active_id', False)
print 'active_id', active_id
if active_id:
print 'output', self.env['opinion'].browse(active_id).notes
return self.env['opinion'].browse(active_id).notes

Related

How do I set a value on a selection via a button

I need to create a button which will define a ticket the value of the state variable to cloturé.
And when a ticket is cloturé, it will on read only.
How can i do it ?
The ticket's model is helpdesk.ticket
view.xml :
<?xml version='1.0' encoding='UTF-8'?>
<odoo>
<record id="helpdesk_ticket_view_form_inherit_header_modifie" model="ir.ui.view">
<field name="name">helpdesk.ticket.modifie.header</field>
<field name="model">helpdesk.ticket</field>
<field name="inherit_id" ref="helpdesk_fsm.helpdesk_ticket_view_form" />
<field name="arch" type="xml">
<xpath expr="//button[#name='action_generate_fsm_task']" position="attributes" >
<attribute name="string">Planifier tache</attribute>
</xpath>
</field>
</record>
</odoo>
ticket.py :
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class ticket_inherit(models.Model):
_inherit = "helpdesk.ticket"
state = fields.Selection(['test','annulé','cloturé'],'selection')
#What i want to do
def cloture_le_ticket(self):
state = 'cloturé'
You can just use write().
state = fields.Selection(string="State", selection=[
('test', 'Test),
('annulé', 'Annulé'),
('cloturé', 'Cloturé')
])
def cloture_le_ticket(self):
self.write({
'state': 'cloturé'
})
To force the ticket to be read-only:
def write(self, vals):
for record in self:
if record.state == 'cloturé':
raise exceptions.UserError("Sorry but the ticket is read only")
return super(HelpdeskTicket, self).write(vals)

Create custom excel report from wizard in odoo 15

I am trying to generate an excel report from wizard using report_xlsx module but i am getting below error.
Traceback (most recent call last):
File "/home/kabeer/Projects/Odoo15ce/odoo/custom_addons/report_xlsx/controllers/main.py", line 76, in report_download
response = self.report_routes(
File "/home/kabeer/Projects/Odoo15ce/odoo/http.py", line 535, in response_wrap
response = f(*args, **kw)
File "/home/kabeer/Projects/Odoo15ce/odoo/custom_addons/report_xlsx/controllers/main.py", line 32, in report_routes
data.update(json.loads(data.pop("options")))
ValueError: dictionary update sequence element #0 has length 10; 2 is required
Here is what i did.
*.xml
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="open_purchase_order_print_menu" model="ir.actions.report">
<field name="name">Open PO</field>
<field name="model">open.po</field>
<field name="report_type">xlsx</field>
<field name="report_name">transight.open_po</field>
<field name="report_file">transight.open_po</field>
<field name="print_report_name">'Purchase Order'</field>
<!-- <field name="binding_model_id" ref="purchase.model_purchase_order"/> -->
<field name="binding_type">report</field>
</record>
<record id="open_po_view_form" model="ir.ui.view">
<field name="name">open.po.form</field>
<field name="model">open.po</field>
<field name="arch" type="xml">
<form string="Open PO">
<group>
<field name="mode" required="1"/>
</group>
<group col="4">
<field name="purchase_order_id"
widget="many2many_tags"
attrs="{'invisible':[('mode','=','partnumber')]}"/>
<field name="partnumber" attrs="{'invisible':[('mode','=','po')]}"/>
</group>
<footer>
<button string="Print" name="action_print" type="object" class="btn-primary"/>
<button string="Cancel" class="btn-secondary" special="cancel"/>
</footer>
</form>
</field>
</record>
<record id="action_open_po" model="ir.actions.act_window">
<field name="name">Open PO</field>
<field name="res_model">open.po</field>
<field name="view_mode">form</field>
<field name="target">new</field>
</record>
<menuitem id="menu_open_po_action" name="Open PO" parent="mrp.menu_mrp_configuration" action="action_open_po" sequence="4"/>
</odoo>
*.py
from odoo import fields,models,api,_
class OpenPOXlsx(models.AbstractModel):
_name = 'report.transight.open_po'
_inherit = 'report.report_xlsx.abstract'
def generate_xlsx_report(self, workbook, data, partners):
print('data',data)
for obj in partners:
report_name = 'Excel Report test'
# One sheet by partner
sheet = workbook.add_worksheet(report_name[:31])
bold = workbook.add_format({'bold': True})
sheet.write(0, 0, 'Hi Am here', bold)
class OpenPO(models.TransientModel):
_name = 'open.po'
_description = 'OpenPO'
purchase_order_id = fields.Many2many('purchase.order',string='Purchase Order')
partnumber = fields.Char(string="Partnumber")
mode = fields.Selection([('partnumber','Part Number'),('po','Purchase Order')],string="Filter by")
def action_print(self):
if self.mode == 'po':
query = """my query %s """
self.env.cr.execute(query,(tuple(self.purchase_order_id.ids),))
datas = self.env.cr.dictfetchall()
print('data---------',datas)
# return self.env.ref('account_batch_payment.action_print_batch_payment').report_action(self, config=False)
return self.env.ref('transight.open_purchase_order_print_menu').report_action(self,data=datas)
The dictfetchall() method returns a list of dicts and report_action is expecting data (datas) to be a dict.
In previous Odoo versions, we pass record data using form key, for example:
datas = {
'ids': active_ids,
'model': 'hr.contribution.register',
'form': self.read()[0]
}
To fix this issue, add the fetched values to datas:
values = self.env.cr.dictfetchall()
datas['values'] = values
Then use values key in generate_xlsx_report method
Make sure that datas is a dictionary before calling report_action

Sequencing in odoo 10

I am trying to create a sequence in odoo here is my xml file
<record model="ir.sequence" id="connection_sequence_id">
<field name="name">New Connections Sequence</field>
<field name="code">ftth.connection</field>
<field name="prefix">FTTH</field>
<field name="padding">6</field>
<field name="company_id" eval="False" />
</record>
I have created a field for it in my .py file
my_seq = fields.Char(string="sequence", default=lambda self: _('New'))
and overiddeen the create function by using the following code
#api.model
def create(self, vals):
if vals:
vals['my_seq'] = self.env['ir.sequence'].next_by_code('ftth.connection') or _('New')
result = super(NewConnections, self).create(vals)
return result
but my code is not generating a sequence instead it gives ftth.connection.(sequence number).what might be wrong with my code.please assist
use super to customize your create function, this an example:
#api.model
def create(self, vals):
if vals:
seq = self.env['ir.sequence']
vals['my_seq'] = seq.next_by_code('ftth.connection') or _('New')
return super(ObjectName, self).create(values)

Access inherited field of a model from a view

I'm working on OpenERP7, trying to access a related field located in a parent model of said related model. If someone at this point understand something, you're way smarter than I am, so i will just put the example of what i'm trying to achieve :
My model :
class trench(osv.osv):
_name = 'trench'
_inherit = 'common'
_columns = {
'trench_lines': fields.one2many('trench.line', 'trench_id', 'Trench Lines'),
'trench_depth': fields.one2many('trench.depth', 'trench_id', 'Trench Depth'),
}
trench()
class trench_common(osv.osv):
_name = 'trench.common'
def compute_vals(self, cr, uid, ids, field_name, arg, context):
...
def on_change_values(self, cr, uid, ids, context=None):
...
_columns = {
'trench_id': fields.many2one('trench', 'Trench', ondelete='cascade', required=True),
'length' : fields.function(compute_vals, type='float', string="Length", method=True, store=True),
}
trench_common()
class trench_line(trench_common):
_name = 'trench.line'
_inherit = 'trench.common'
trench_line()
class trench_dig_common(trench_common):
_name = 'trench.dig.common'
_inherit = 'trench.common'
_columns = {
'length' : fields.float('Length', digits=(6,3)),
'height' : fields.float('Height', digits=(6,3)),
'total_m3' : fields.float('Total m3', digits=(6,3)),
'observation' : fields.text('Observation'),
}
trench_dig_common()
class trench_depth(trench_dig_common):
_name = 'trench.depth'
_inherit = 'trench.common'
trench_depth()
My view :
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="trench_form" model="ir.ui.view">
<field name="name">trench.form</field>
<field name="model">trench</field>
<field name="inherit_id" ref="common_form" />
<field name="arch" type="xml">
<group string="Worksite" position="after">
<separator string="Progress" />
<field name="trench_lines">
<tree editable="bottom">
<field name="length"/>
</tree>
</field>
<separator string="Cumulate Length" />
<field name="total_length"/>
<separator string="Trench Particularity" />
<notebook>
<page string="Surdepth">
<field name="trench_depth">
<tree editable="bottom">
<field name="height"/>
</tree>
</field>
</page>
</notebook>
</group>
</field>
</record>
</data>
</openerp>
My error :
except_orm: ('View error', u"Can't find field 'height' in the following view parts composing the view of object model 'qhse.trench':\n * trench.form\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model")
2015-05-21 07:56:28,631 13918 ERROR ahak_production openerp.tools.convert: Parse error in trench_view.xml:4:
So, i'm figuring i can't access a field of a model with so many layers, but is there a way to achieve this, and if so, how? I'm trying to make something DRY, but always end up duplicating code with OpenERP.
Thanks for reading.
You need to define your last class as below.
class trench_depth(trench_dig_common):
_name = 'trench.depth'
_inherit = 'trench.dig.common'
trench_depth()
Then after you can access all fields which are available inside "trehch.dig.common" model.

openerp to download attendance machine

Please me to solve this problems. I'm using openerp to download attendance machine and insert that data into my table but i have to view the data from the machine into grid using using one2many field how could I passing the data after I downloaded this my script. I'm using zkclock module to get the data.
hr_machinezem560.py
....
import zkclock
import from osv import osv, fields
....
class hr_machinezem560(osv.osv):
_name = "hr_machinezem560"
_columns = {
'date_from':fields.date("Date From"),
'date_to':fields.date("Date To"),
'proses_id':fields.one2many('hr.machinezem560_details', 'proses_id', 'Prosess Download')
}
def action_download(self, cr, uid, ids, context=None):
domain = {}
params = self.browse(cr, uid, ids, context=context)[0]
start_date = date_object = datetime.datetime.strptime(params.date_from, '%Y-%m-%d')
end_date = date_object = datetime.datetime.strptime(params.date_to, '%Y-%m-%d')
date_list = [dt.strftime("%Y-%m-%d") for dt in rrule(DAILY, dtstart=start_date, until=end_date)]
host = '192.168.1.201'
port = 4370
password = ''
s, r = zkclock.connect(host, port, password)
r = zkclock.disable(s, r)
r, userdata = zkclock.get_user_data(s, r)
r, logdata = zkclock.get_log_data(s, r)
r = zkclock.enable(s, r)
r = zkclock.disconnect(s, r)
if userdata and logdata:
logdata = zkclock.assemble_log_data_from_packets(logdata)
users = zkclock.unpack_users_to_dict(userdata)
logging.debug(users)
loglist = []
while((len(logdata)/LOG_DATA_SIZE) >=1):
loglist.append(logdata[:LOG_DATA_SIZE])
logdata = logdata[LOG_DATA_SIZE:]
logs = []
for i in loglist:
log_entry = zkclock.unpack_log(i)
timestamp = zkclock.decode_time(log_entry.time)
verification_method = log_entry.decode_verified()
try:
user_name = users[log_entry.uid].name
except KeyError:
user_name = "Unknown user: %s" % log_entry.uid
logs.append([timestamp,str(log_entry.uid), verification_method])
attance_det = self.pool.get("hr.machinezem560_details")
for log in logs:
if log[0].strftime('%Y-%m-%d') in date_list:
values = {
'employee': log[1],
'timesheet': log[0],
'status':log[2]
}
attance_det.create(cr, uid, values, context=context)
hr_machinezem560()
class hr_machinezem560_details(osv.osv):
_name = "hr.machinezem560_details"
_columns = {
'employee': fields.char("Employee Name", size=80),
'timesheet':fields.datetime("Time Sheet"),
'status': fields.char("Status", size=10),
'proses_id':fields.many2one('hr_machinezem560','Prosess Download')
}
hr_machinezem560_details()
view:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="hr_batch_machine_view_form" model="ir.ui.view">
<field name="name">Attendance Machine Batch Process</field>
<field name="model">hr_machinezem560</field>
<field name="type">form</field>
<field name="arch" type="xml">
<form string="Download ZEM560 Data" version="7.0">
<group name="up">
<label for="date_from" string="Timesheet Period"/>
<div>
<field name="date_from" class="oe_inline"/> to <field name="date_to" class="oe_inline"/>
<div class="oe_right oe_button_box" name="right_top_button">
<button name="action_download" string="Download" type="object"/>
</div>
</div>
</group>
<group name="down">
<field name="proses_id" colspan="3" nolabel="1" readonly="1">
<tree string="Attendance Data">
<field name="employee"/>
<field name="timesheet"/>
<field name="status"/>
</tree>
</field>
</group>
</form>
</field>
</record>
<record id="action_batch_hr_machine_view" model="ir.actions.act_window">
<field name="name">Attendance Machine Batch Proses</field>
<field name="res_model">hr_machinezem560</field>
<field name="view_type">form</field>
<field name="view_mode">form</field>
<field name="target">new</field>
</record>
<menuitem
id="menu_hr_absensiRoot"
name="Absensi"
sequence="3"
parent="hr.menu_hr_root"
/>
<menuitem
id="menu_hr_mesin_Absensi"
name="Mesin Absensi ZEM560"
sequence="1"
parent="menu_hr_absensiRoot"
action="action_batch_hr_machine_view"
/>
</data>
</openerp>