How to store the current logged user id or active user id in odoo 9?

10.5k Views Asked by At

In expenses, anyone has to approve the expense list, I want to display which user is Approved that?

I just select all res.users as one2many

approved_by=fields.Many2one('res.users','Approved By')

In XML

<field name="approved_by" />

Here it will display all users. But I want to display only logged user and it must be selected as default.

3

There are 3 best solutions below

0
On BEST ANSWER

The Environment stores various contextual data used by the ORM. For more details Odoo Environment

Try with following code.

approved_by = fields.Many2one('res.users','Approved By', default=lambda self: self.env.user)

EDIT

With following code, we can also get User id.

approved_by = fields.Many2one('res.users','Approved By', default=lambda self: self.env.uid)
0
On

Define a default value on the field, the default value will be a function that returns the current user's id which can be accessed with self.env.uid

def get_user_id(self):
    return self.env.uid

approved_by=fields.Many2one('res.users','Approved By', default=_get_user_id)

If you want the field to be edited/changed just set readonly=True

1
On

You can use below code:

context = self._context
current_uid = context.get('uid')
user = self.env['res.users'].browse(current_uid)