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")
    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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *