Restrict write permissions for a field - Odoo 15

196 Views Asked by At

How can I restrict the write permissions for a field to a specific group ?

I want to check if a user is in a specific group with id 46. If the user is in this group, he should be allowed to write in this field. If he is not in this group, he should not be allowed to write.

The field is a custom field, editing the domain with the studio app I think I should avoid.

My field:

<field name="customer_codename" placeholder="Codename" attrs="{'invisible':['|',('customer_rank','=', 0),('is_company','=', False)]}"/>

I tried the following, but it did not work: I created a new field using the studio app. Field type is boolean. In the advanced properties I wanted to define the compute for the field. In dependencies I gave "user_id" and in the compute field I gave

for record in self:
  user_id.has_group('__export__.res_groups_46_eff9dc52')

The boolean field should be set to true if the user is in a certain group.

1

There are 1 best solutions below

2
Dennis Quan On

Not sure if I can give you the best answer there is. But for me, I'd personally create a Boolean field in the view's associated model, with its default field a lambda function checking if the user belongs to the groups you mentioned.

Assuming groups_id is the name of the user groups in model res.users, we have:

class ResUsers(models.Model): 
    _inherit = "res.users" 

    can_write_codename = fields.Boolean(default=lambda self: self.groups_id in ("model_name.group_name"))

Then in your xml file, you can include can_write_codename inside attrs, like this:

  <field name="customer_codename" placeholder="Codename" attrs="{'invisible':['|',('customer_rank','=', 0),('is_company','=', False)], 'readonly': [('can_write_codename', '=', 'True')]}"}"/>