Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
5 Trả lời
10115 Lượt xem

I have a few fields in a form that I want to keep readonly unless user is admin for my module...

in the xml:

<field name="name" attrs="{'readonly':[('user_is_admin', '=', False)]}"/>

in my .py:

user_is_admin = fields.Boolean(compute="_compute_user_is_admin", store=False)

def _compute_user_is_admin(self):
        self.user_is_admin = self.env.user.has_group('towers.group_mymodule_admin')

Works just fine, until I try to create a new record, then even if I'm admin those fields are read only. I tried displaying the field user_is_admin it is false when creating a new record (I'm guessing that makes sense since no data for that record has been created yet) if I save the record and edit it then I can edit those fields...

Any way around this? ...BTW only admin user can create a new record if that helps...

Ảnh đại diện
Huỷ bỏ

user = self.env['res.users'].browse(self._uid)

user.has_group('base.group_erp_manager')

I don't think this is a problem with self.env.user.has_group - the problem is that user_is_admin isn't computed until the record is saved.  

Tác giả Câu trả lời hay nhất

Since non admin users are not able to create new records, I resolved it by checking id to see if it's creating a new record:

<field name="name" attrs="{'readonly':[('user_is_admin','=',False),('id','>',0)]}"/>

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

Hi 
you can Start by converting your field to compute field and pass the method to it
and after that pass you depends to the method like this:
api.depends_context('uid')


after this the method will work just fine


Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

Hi you can add default like this

user_is_admin = fields.Boolean(compute="_compute_user_is_admin", store=False, default= lambda self: "_compute_user_is_admin")

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

I don't think this is a problem with self.env.user.has_group - the problem is that user_is_admin isn't computed until the record is saved.  

Possible workaround: set a user-defined default (for the Administrator only): 

user_is_admin = true
Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

Have you tried with sudo().

      self.user_is_admin = self.env.user.sudo().has_group('towers.group_mymodule_admin')

Ảnh đại diện
Huỷ bỏ
Tác giả

Would that cause it to compute before there is a record saved?