How to get Current user

How to get who is currently login in Django?

See the docs for: Authentication in web requests.

1 Like

Ok. Thank you. But this is user authentication. I meant with django sessions.

You don’t retrieve the user from the session. You retrieve it from the request, as documented.

1 Like

Or I may be not understanding the question. What goal or objective are you trying to achieve?

def home(request):
     user = request.user #the user
     email = #their email
     username = user.username #their username

Is that what you are looking for?

No. I want to get who are online in my platform like WhatsApp and Facebook. To see the user that is online that a moment he/she log in.

I appreciate your kindness in this forum.

That’s actually not a simple question to answer on a traditional (non-websocket / non-polling) web site.
Outside of “live” sites that rely heavily on JavaScript, your browser doesn’t stay connected to the web site. The browser requests a page, gets a response, and then disconnects. There’s no such thing as “who is online” that can be answered.

So, the question becomes, what JavaScript environment / library are you using? Are you using Django Channels or something else? The answer to your question is going to depend on that.

1 Like

As Ken said, that’s not easy to implement just on Django. A quick, but not an ideal implementation is to initialize an empty list in your views as a global variable, and set a signal on logins to add users to that list on login (and remove them when they log out).

Here is the docs for logged in/logged out signals: django.contrib.auth | Django documentation | Django

1 Like

That’s not going to work in any production-quality deployment environment that works with multiple workers or that periodically restarts the workers. “Global” variables are only global to one instance and only one instance is going to receive any particular signal. (And that would be the instance in which the process triggering that signal occurs.)

Persistent data across workers must be stored externally to the Django process. (Database, redis, memcache, etc)

I would never rely on that signal for anything. It’s too easy for a person to just close their tab or browser to leave a site. Our experience is that fewer than 20% of all “login” page requests can be matched to a corresponding “logout” page request.

1 Like

Thank you for the response, sir, I really appreciate it.