Friday, 13 October 2017

How to Get Currently Logged In User in Odoo



In this tutorial, i will teach you the simplest way to get the currently logged in user in Odoo. These tutorial is based on version 8, 9 and 10.

Let's get to it...

To get the currently logged user in Odoo, i will create a small method that gets the logged in user and default the method on a field.

def _employee_get(self):
record = self.env['res.users'].search([('name', '=', self.env.user.name)])
return record.name
view raw logged user hosted with ❤ by GitHub

Now that you have the method, all you need is to default the method on a field. The field you are returning the method on, can either be Char or a Many2one field, it's your choice


logged_user = fields.Char(string="Logged User", default=_employee_get)
view raw field hosted with ❤ by GitHub
If the field is Char, then you need to return record.name, as shown in the code, because the model it searches returns an id value, so you need the name to be able to get the exact value from the model.

If your field is Many2one, then you dont need to return record.name, all you need is just to return record alone, and the Many2one field will do the magic.

Now, let's put the pieces together...

from odoo import fields, models, api
class RecruitmentForm(models.Model):
_name = 'recruitment.application'
# method to return logged in user on a Char field
def _employee_get(self):
record = self.env['res.users'].search([('name', '=', self.env.user.name)])
return record.name
logged_user = fields.Char(string="Logged User", default=_employee_get) # Char field
# method to return logged in user on a Many2one field
def _employee_get(self):
record = self.env['res.users'].search([('name', '=', self.env.user.name)])
return record
logged_user = fields.Many2one('res.users', string="Logged User", default=_employee_get) # Many2one
view raw full_code hosted with ❤ by GitHub

No comments:

Post a Comment