Extending create() and write()
To include any additional functionality while creating a record of the model, we can extend a model's create() function.
As an example, let's add a "notes" field to the "sale.order.".
In this instance, users who are not members of the "Administration/Access Rights" group will see a "UserError" while attempting to update the notes field.
class SaleOrder(models.Model):
_inherit ='sale.order'
notes = fields.Text(string='Notes')
def create(self,vals):
res = super(SaleOrder,self).create(vals)
if 'notes' in vals and not self.env.user.has_group('base.group_erp_manager'):
raise UserError(_("You cannot edit the field 'notes'"))
return res
We can accomplish the same thing as an illustration of the write() function. We check the field's group and occurrence in the vals to write before writing, and if something goes wrong, we raise a UserError exception.
def write(self, vals):
res = super(SaleOrder, self).write(vals)
if 'notes' in vals and not self.env.user.has_group(
'base.group_erp_manager'):
raise UserError(_("You cannot edit the field 'notes'"))
return res