save in a function onchange (Odoo) - odoo

I have a field type char "name" and a function onchange for this field.
I want save the register complete when i modified the field "name"
Something like:
#api.onchange('name')
def _onchange_name(self):
#Save the register on the BBDD (like press the save button)

register = fields.Float()
#api.depends('name')
def _compute_register(self):
self.register = something

I think you need to add it in your def write() method
#api.multi
def write(self, vals):
if vals.get('name'):
#insert code here

Related

Integrating custom module with odoo website

I have a custom module called admission form with some fields suppose name, phone, email, etc. how to add this form to website module using templatr to work like contact form in contact us page when filled data is automatically created in new leads. instead of leads i want it to transfer the information to my custom module.
Summary: instruction to relate website to custom module.
class AdmissionForm(models.Model):
_name = 'admission.form'
name = fields.Char()
phone = fields.Integer()
email = fields.Char()
faculty = field.Many2one('res.faculty')
In ODOO Whenever you want to performe some task at the time of creation ,then you must override create method in your model (:admission.form).
Let say you want to create a partner just after creation of the record in admission.form model then follow these steps:
Override create method .
Call the super with the argument and hold it value in result.
Now do your task .
return result.
Code snippet:
#api.model
def create(self, vals):
result = super(AdmissionForm, self).create(vals)
new_vals = dict(name=result.name,
phone=result.phone,
email=result.email,
is_company=1,
supplier=1,
customer=1,
)
self.env['res.partner'].create(new_vals)
return result
In case if you want to do some task before creation of record then follow these steps:
Override create method .
Do your task .
Call the super with the argument and return it.
#api.model
def create(self, vals):
new_vals = dict(name=vals.get('name'),
phone=vals.get('phone'),
email=vals.get('email'),
is_company=1,
supplier=1,
customer=1,
)
partner=self.env['res.partner'].create(new_vals)
return super(AdmissionForm, self).create(vals)

How to post a message in chatter during create method in Odoo?

I was writing create method for my own custom module.
def create(self, cr, uid,ids, context=None):
self.message_post(cr, uid, ids, body=_("Form Page created"), context=None)
but i am getting the following error when saving
AssertionError: Invalid thread_id; should be 0, False, an ID or a list with one ID
or sometimes
TypeError: create() got multiple values for keyword argument 'context'
i just want to post a message when it is created
Openerp 7 Create Method
def create(self, cr, uid, vals, context=None):
new_id = super(CRM_Lead, self).create(cr, uid, vals, context=context)
return new_id
odoo 8 Create Method:
class ClassName(models.Model):
_inherit = "model.name"
#api.model
def create(self, vals):
rec = super(ClassName, self).create(vals)
# ...
return rec
Make sure you use the exact name of the python class in the super function and also that you return the same object you get from it.
Track Visibility
You can set a mail.message.subtype that depends on an other to act through a relation field.
For better understanding track visibilty Refer This Link
There is two type fileds of track visibility
track_visibility='always'
track_visibility='onchange'

Passing context to qweb report for managing table visibility - odoo

How can we pass context value to qweb report so that i can control the visibility of tables. I have a qweb report with lot of tables. Depending on the selection list, i want to control the view of these tables in qweb report. So my option was to control using context. But didn't find any way to pass the context. If there is any other opinion, please share.
Create parser class first
import time
from openerp.osv import osv
from openerp.report import report_sxw
class sale_quotation_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(sale_quotation_report, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
‘key’: value,
‘function_name’: self.function_name,
})
def function_name(self):
### add some code if required..
Then define another class
class report_saleorderqweb(osv.AbstractModel):
_name = ‘module_name.report_sale_order_qweb’
_inherit = ‘report.abstract_report’
_template = ‘module_name.report_sale_order_qweb’
_wrapped_report_class = sale_quotation_report
Then you can call the localcontext method in that way
<span t-esc=”function_name(parameter)”/>
Refer our blog on Qweb report
Your question is not very clear on what exactly you want. For instance, I dont know what you mean by "Depending on the selection list", so I assume you have a wizard that prompts the user to select some options. If that is the case, you can pass the selection variable inside the data dictionary in the return statement of your print function.
def print_report(self, cr, uid, ids, context=None):
if context is None:
context = {}
datas = {'ids': context.get('active_ids', [])}
res = self.read(cr, uid, ids, ['date_start', 'date_end', 'user_ids'], context=context)
res = res and res[0] or {}
datas['form'] = res
if res.get('id',False):
datas['ids']=[res['id']]
return self.pool['report'].get_action(cr, uid, [], 'point_of_sale.report_detailsofsales', data=datas, context=context)
This passes the user selection under data['form']. You can then access the selections in qweb as data['form']['date_start']

Is there any way to call a function when a record is requested to be shown in a form view?

I would like to update every record when it is shown in form view. Is there anyway to define some sort of a callback to update the record BEFORE it is shown?
One method that I could think of is by adding a dummy field to form view with an on_change attribute. But it feels kinda hacky.
You can use function field. Function is called when the form loading and at the time of new record creation before and after.
When you create a new record this function field will take value as a William and after saving value will change and become odedra
Here is example of char return type of function :
def _default_get(self, cr, uid, context=None):
print " This function called before new record create "
res = 'William'
return res
def _set_value(self, cr, uid, ids, name, args, context=None):
print " This function called at time of saving record and form view load "
res = {}
for i in self.browse(cr, uid, ids, context=context):
res[i.id] = 'odedra'
return res
_columns = {
'value': fields.function(_set_value, type='char', string='Value'),
}
_defaults = {
'value': _default_get,
}
NOTE:
As per your requirement, you may change function field return type.
Using a functional field seems odd but then making a read not idempotent is also unusual.
I would set a context in the window action of your form so you can test for it and limit the effect of this and then override the default_get method for new records and the read method for existing records on your model.

django Autocomplete-light how to choose a specific method from a mode

I am new at django and autocomplete-light. I try to get a different fields of the model from autocomplete-light, but it always return the same field. And the reason is because def in the Model defined one field. So I created another def, but can not make autocomplete-light to call that specific def. Here is my code.
models.py:
class Item(models.Model):
...
serial_number=models.CharField(max_length=100, unique=True)
barcode=models.CharField(max_length=25, unique=True)
def __unicode__(self):
return self.serial_number
def bar(self):
return self.barcode
.......
autocomplete_light_registry.py
autocomplete_light.register(Item,
name='AutocompleteItemserial',
search_fields=['serial_number'],
)
autocomplete_light.register(Item,
name='AutocompleteItembarcode',
search_fields=['barcode'],
)
Here is the issue: when I try to get the barcodes from the autocomplete-light, it returns serial_numbers. No matter what I try to get from the Item model, it always returns the serial number. I really appreciate for the answers. Thank you.
Just in case, here is the form.py
forms.py
class ItemForm(forms.ModelForm):
widgets = {
'serial_number': autocomplete_light.TextWidget('AutocompleteItemserial'),
'barcode': autocomplete_light.TextWidget('AutocompleteItembarcode'),
}
Although this is an old post but as I just faced the same issue therefore I am sharing my solution.
The reason autocomplete is returning serial_number is because django-autocomplete-light uses the __unicode__ method of the model to show the results. In your AutocompleteItembarcode all that is being done is autocomplete-light is searching by barcode field of Item.
Try the following.
In app/autocomplete_light_registry.py
from django.utils.encoding import force_text
class ItemAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['serial_number']
model = Item
choices = Item.objects.all()
def choice_label(self, choice):
"""
Return the human-readable representation of a choice.
"""
barcode = Item.objects.get(pk=self.choice_value(choice)).barcode
return force_text(barcode)
autocomplete_light.register(ItemAutocomplete)
For more help you can have a look at the source code.