Set default date in OpenERP - odoo

I'm working at creating a module for OpenERP 7 to set Today's Date as default value when creating a new Partner. I've installed the module, restarted the Openerp service and defaults aren't changed a bit. (I'd included a "goofball" field and bogus default data for the website field to make sure it's not a python lambda code problem. It wasn't...) Here's my code in partner.py:
from osv import osv, fields
import datetime
class res_partner(osv.osv):
_inherit = 'res.partner'
_columns = {"goofball":fields.char('goofball', size=15)}
_defaults = {
'website': 'www.veppsight.com',
'date': lambda *a: datetime.date.today().strftime('%Y-%m-%d'),
}
The default data isn't entered for the website & date fields and the "goofball" field isn't create in the database which I verified in psql. What am I doing wrong?

Since V6.1 there is a new function to deal with today's date, called context_today.
You can check background on this at the following link...
http://openerp-expert-framework.71550.n3.nabble.com/Bug-925361-Re-6-1-date-values-that-are-initialized-as-defaults-may-appear-as-quot-off-by-one-day-quoe-td3741270.html
Based on that, you can just use...
_ defaults = {
'date1': fields.date.context_today,
}
Regards,
-Mario

Import time and In the defaults
_defaults = {
'website': 'www.veppsight.com',
'date': lambda *a: time.strftime('%Y-%m-%d'),
}

Use following code :
from osv import osv, fields
import time
class res_partner(osv.osv):
_inherit = 'res.partner'
_columns = {"goofball":fields.char('goofball', size=15)}
_defaults = {
'website': 'www.veppsight.com',
'date1': time.strftime('%Y-%m-%d'),
}
AND IF POSSIBLE RENAME FIELD NAME DATE TO SOMETHING ELSE. AS DATE IS DT IN POSTGRESQL
Thank You

_defaults = {
'date': lambda self,cr,uid,context={}: context.get('date', fields.date.context_today(self,cr,uid,context=context)),
or
'date': lambda self, cr, uid, context={}: context.get('date', time.strftime("%Y-%m-%d %H:%M:%S")),
or
'date' : fields.date.context_today,
}
Lambda is a in line or anonymous function in python.

How about this:
from osv import osv, fields
import time
class res_partner(osv.osv):
_inherit = 'res.partner'
_columns = {"goofball": fields.char('goofball', size=15)}
_defaults = {
'website': 'www.veppsight.com',
'date1': lambda *a: time.strftime('%Y-%m-%d'),
}
res_partner()

Related

Odoo TypeError: 'NewId' object is not iterable

I am trying to create an activity when a stage change occurs but keep getting TypeError: 'NewId' object is not iterable .
I figured out that #onchange creates a new object which replaces self and I am guessing this is the errors cause.
Here is my code:
class ProjectSetAndDateType(models.Model):
_inherit = 'project.task.type'
last_stage = fields.Boolean(string="Fertigstellungsstufe")
class ProjectSetEndDate(models.Model):
_inherit = 'project.task'
#api.onchange('stage_id')
def _set_end_date(self):
if self.stage_id.last_stage:
self.kanban_state = "done"
self.date_finished = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
activity_deadline = datetime.now() + timedelta(days=30)
data = {
'res_id': self._origin.id,
'res_model': 'project.task',
'res_model_id': self.env['ir.model'].search([('model', '=', 'project.task')]).id,
'user_id': self._origin.project_id.user_id.id,
'summary': 'Aufgabe archivieren nach Fertigstellung',
'activity_type_id': self.env.ref('project_set_end_date.mail_set_end_date_archive').id,
'date_deadline': activity_deadline
}
self.env['mail.activity'].create(data)
'NewId' object is an recordset, when you are creating any new record odoo will store it in newid class , not in database and you are trying to write the kanban_state, date_finished in the record which is not yet created.
I suggest you to change the logic and rewrite this code on the write or create method,
Note: make sure you don't create any record on onchange method because it is very risky and not user friendly.
I rewrote it to this, now it is working as expected.
from odoo import models, fields, api
from datetime import timedelta
from datetime import datetime
class ProjectSetAndDateType(models.Model):
_inherit = 'project.task.type'
last_stage = fields.Boolean(string="Fertigstellungsstufe")
class ProjectSetEndDate(models.Model):
_inherit = 'project.task'
#api.multi
def write(self, vals):
if 'stage_id' in vals:
final_stage = self.env['project.task.type'].search([('id', '=', vals['stage_id'])]).last_stage
if final_stage:
vals['kanban_state'] = "done"
vals['date_finished'] = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
activity_deadline = datetime.now() + timedelta(days=40)
data = {
'res_id': self.id,
'res_model': 'project.task',
'res_model_id': self.env['ir.model'].search([('model', '=', 'project.task')]).id,
'user_id': self.project_id.user_id.id,
'summary': 'Aufgabe archivieren nach Fertigstellung',
'activity_type_id': self.env.ref('project_set_end_date.mail_set_end_date_archive').id,
'date_deadline': activity_deadline
}
self.env['mail.activity'].create(data)
res = super().write(vals)
return res

How to change the default value of a property field in Odoo (old API)?

I'm trying to change the default value of some property fields such as: 'cost_method', 'product_type' and 'valuation' of the 'product' module but I can only change the non-property fields only.
What I tried:
- I created a new module and inherited the 'product.template' model and overridden the '_default' dictionary only but it didn't work.
I created new fields with the same name but of another type (selection) not property but neither did this work.
The code:
_name = "product.template"
_inherit = "product.template"
_columns = {
'cost_method': fields.selection([('average', 'Average Price'),('standard', 'Standard Price'), ('real', 'Real Price')])
,'type': fields.selection([('product', 'Stockable Product'),('consu', 'Consumable'),('service','Service')], 'Product Type', required=True, help="Consumable are product where you don't manage stock, a service is a non-material product provided by a company or an individual.")
,'company_id': fields.many2one('res.company', 'Company', required=False)
}
_defaults = {
'company_id': False
,'type' : 'product'
, 'cost_method': 'average'
, 'barcode':'555'
}
Use only _inherit="product.template". In your case you don't need the _name property.
Did you add your py. File to your __init__.py?
Did you set the correct dependencies in your __openerp__.py. In your case "product"?
Hope that helps you. Let me know.
EDIT:
I could reproduce your problem. My Code for testing
# -*- coding: utf-8 -*-
from openerp.osv import osv, fields
class product_template(osv.osv):
_name = "product.template"
_inherit = "product.template"
_columns = {
'cost_method': fields.selection([('average', 'Average Price'),('standard', 'Standard Price'),('real', 'Real Price')]),
'type': fields.selection([('product', 'Stockable Product'),('consu', 'Consumable'),('service','Service')],'Product Type', required=True, help="Consumable are product where you don't manage stock, a service is a non-material product provided by a company or an individual.") ,
'company_id': fields.many2one('res.company', 'Company', required=False)
}
_defaults = {
'company_id': False,
'type' : 'consu',
'cost_method': 'average',
'barcode':'555'
}
Here the type-field never had the consu value. In my case I could solve the problem by opening the menu Settings -> Technical Settings -> Actions -> User-defined Defaults. I deleted all entries where the name is type and modelname is product.template.
Now if I create a new product the default type is consu. Same behaviour with cost_method-field.

Custom field default value - populate with other entries from same field

I have created a custom module with extra fields on the product screen. I am trying to have the default value be a drop down with all of the entries already submitted to that field or the option to create a new entry (same as the default value when adding a product to a BOM).
class product_part_detail(osv.osv):
_inherit = 'product.template'
_columns = {
'x_mfrname1': fields.char('P/N'),
}
_defaults ={
'x_mfrname1': get_default_name,
}
def get_default_name(self):
return "test"
I tried creating a many2one field that refers to a field in a different table but I keep getting an error when trying to install the module. Below is the updated code that I am having issues with. Thanks in advance!
class product_part_detail(osv.osv):
_inherit = 'product.template'
_name = 'product.part.detail'
_columns = {
'x_mfrname1': fields.many2one('product.part.detail.fill', 'x_mfrname1id'),
'x_mfrname2': fields.many2one('product.part.detail.fill', 'x_mfrname1id'),
}
class product_part_detail_fill(osv.osv):
_name = 'product.part.detail.fill'
def _sel_func(self, cr, uid, context=None):
obj = self.pool.get('product.part.detail')
ids = obj.search(cr, uid, [])
res = obj.read(cr, uid, ids, ['x_mfrname1', 'x_mfrname2'], context)
res = [(r['x_mfrname1'], r['x_mfrname2']) for r in res]
return res
_columns = {
'x_mfrname1id': fields.one2many('product.part.detail', 'x_mfrname1', 'x_mfrname2', selection=_sel_func),
}
A couple of things. The idea of a drop down of the values they have previously entered requires a many2one field. You would create another model and then make x_mfrname1 a many2one to that table. As long as the user has create access on that table they will get a create option on the drop down to key new values.
One other item, as you are using the pre-8 API, the method signature of your default method should be:
def get_default_name(self, cr, uid, context=None):

Openerp - AttributeError in function of stock.picking.in

Really struggling with this one:
I have inherited from stock.picking.in and have added a few columns. I then added a function field.
In the function that the function field refers to, it works if I do not use any attribute from the stock.picking.in object. The moment I use any value from the object, it starts giving 'AttributeError: ' and some attribute at random. It doesn't specify any other reasons or causes.
Code:
class stock_picking_custom(osv.osv):
_name = 'stock.picking.in'
_inherit = 'stock.picking.in'
_table = "stock_picking"
def calc_royalty(self, cr, uid, ids, field_name, arg, context=None):
if not ids: return {}
res = {}
for line in self.browse(cr, uid, ids, context=context):
res[line.id] = 0 #line.royalty_rate * line.loading_netweight
return res
_columns = {
'loading_netweight': fields.float('Net weight at loading', digits=(16,2), help="Net weight at loading (interior weight)"),
'royalty_date': fields.date('Royalty Issue date'),
'royalty_number' : fields.char('Royalty Number', size=64),
'royalty_rate' : fields.float('Royalty Rate (p. ton)', digits=(16,2)),
'royalty_amount' : fields.function(calc_royalty, type='float', digits=(16,2), string='Royalty Amount', store=True, select=True)
}
stock_picking_custom()
I have commented out the line that I want to use. The moment I put this line back in the code, it would give attribute error on royalty_date (for example) which is not even mentioned in the function.
Please guide.
EDIT: I tried the exact same code with purchase.order and it works perfectly. What is different about stock.picking.in?
Thanks
Ok, found the answer in stock module in delivery addon. So this is a framework limitation issue related to inheritance order etc.
Sharing here in case someone ends up in a similar situation.
To solve, I repeated the same fields in stock.picking and stock.picking.in. Then I called the calc function of the picking class from the picking.in class.
Code:
class stock_picking_custom(osv.osv):
_name = 'stock.picking'
_inherit = 'stock.picking'
def calc_royalty(self, cr, uid, ids, field_name, arg, context=None):
if not ids: return {}
res = {}
for line in self.browse(cr, uid, ids, context=context):
res[line.id] = line.royalty_rate * line.loading_netweight
return res
_columns = {
'loading_netweight': fields.float('Net weight at loading', digits=(16,2), help="Net weight at loading (interior weight)"),
'royalty_date': fields.date('Royalty Issue date'),
'royalty_number' : fields.char('Royalty Number', size=64),
'royalty_rate' : fields.float('Royalty Rate (p. ton)', digits=(16,2)),
'royalty_amount' : fields.function(calc_royalty, type='float', digits=(16,2), string='Royalty Amount', store=True, select=True)
}
stock_picking_custom()
class stock_picking_in_custom(osv.osv):
_name = 'stock.picking.in'
_inherit = 'stock.picking.in'
_table = "stock_picking"
def calc_royalty(self, cr, uid, ids, field_name, arg, context=None):
return self.pool.get('stock.picking').calc_royalty(cr,uid,ids,field_name,arg,context=context)
_columns = {
'loading_netweight': fields.float('Net weight at loading', digits=(16,2), help="Net weight at loading (interior weight)"),
'royalty_date': fields.date('Royalty Issue date'),
'royalty_number' : fields.char('Royalty Number', size=64),
'royalty_rate' : fields.float('Royalty Rate (p. ton)', digits=(16,2)),
'royalty_amount' : fields.function(calc_royalty, type='float', digits=(16,2), string='Royalty Amount', store=True, select=True)
}
stock_picking_in_custom()
I did not get much time to spend on it but I came to know that line is coming with stock.picking.in object and fields, you defined, are stored in stock_picking table that's why it may going to search that field with stock.picking.in, not getting and error is coming.
There may be issue with fields defined in object and table, but not sure.

One module field use to other module in openerp

I created a field name "link to opportunities" :-
module :- hr.applicant
field type:- many2many
object relation:- crm.lead
and i used in crm.lead module .
Now i want to use this field in "hr.recruitment" .
but i have tried many ways but not success. please tell me. how can use this field in other module like as crm.lead to hr.recruitment
thank you for your timing.
this code i used:-
'sale_o_ids' : fields.related('job_id', 'x_link_to_jobposition',
readonly=True,
relation='crm.lead',
string='Opportunity Name'),
Here is the example:
of many2many
class hr_job(osv.osv):
_inherit = 'hr.job'
_columns = {
'sale_ids': fields.many2many('sale.order', 'hr_job_sale_order_rel', 'job_id', 'sale_id', 'Sale order'),
}
hr_job()
Here created a many2many field of sale.order
Now i want to used the hr.job field in hr.employee.
class hr_employee(osv.osv):
_inherit = "hr.employee"
def _get_sale_order(self, cr, uid, ids, field_name, arg, context=None):
if context is None:
context = {}
result = {}
list_o = []
for order in self.browse(cr, uid, ids, context=context):
for i in order.job_id.sale_ids:
list_o.append(i.id)
result[order.id] = list_o
return result
_columns = {
'sale_order_ids': fields.function(_get_sale_order, type='many2many', relation="sale.order", string="Sale Orders"),
}
hr_employee()
So when you update in the hr.job many2many field then its updated value show in hr.employee object when in job select this job
Another method you can use related
'sale_o_ids' : fields.related('job_id', 'sale_ids',
type='many2many',
readonly=True,
relation='sale.order',
string='Available Sale Order'),
Hope this thing clear to you