Sunday 3 February 2019

How to Validate a User’s Group in Odoo

In this tutorial, we will learn how to validate if a user belongs to a group or not. Checking or validating if a user belongs to a group can be done using the odoo technical method called has_group. The has_group is a method that is attached to the res.users model, which means you can only use this on the res.users model.

How to Check

The first thing to do is to get the Id of the user, it can either be a currently logged in user or another user, just make sure it is a res.users related field. This can be seen below;

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

After you have gotten the Id of the user, the next thing is to utilize the method has_group and that can be done against the variable user, as shown below:

if user.has_group('sale.group_analytic_accounting'):
    print("The User belongs to an Analytic Accounting Group")
else:
    print("Whoops! User does not belong to this Group")

The above shows a checkmate of the user, if the user belongs to the Sales Analytic Accounting Group, then the user will be able to perform some operations and if not, another operation is performed, but in this case the message will be printed on your terminals.

Bonus: I have created a small module, which makes you click on a button on sales orders and the button tells you, if a user belongs to the sales group_analytic_accounting group or not.  Go to Repository

Kindly share your opinion by commenting below, if this helps you, also remember to share.

No comments:

Post a Comment