Check if user is logged in or not django by username

Viewed 1075

In django login, we can type if request.user.is_authenticated to check if the user is logged in. But if we want to check the login status of a particular user by entering the username, we get the following:

#Python
def checkLoginStatus(username):
    #do some checks here....
    return True or False

2 Answers

Django does not keep track of the login state of a user. It keeps track of:

  • Whether a session is valid (not expired, exists in session store, etc)
  • The last time a user authenticated itself and went from not logged in to logged in (via last_login

If you want to keep track of it, you need to do it yourself:

  • Add a userprofile model with a nullable field session_key.
  • Add signal receivers for logged_in and logged_out event.
  • Upon logged_in event, get the session key from request.session (request is passed to the signal) and store it on the profile model
  • Upon logged_out event, set the session_key to None
  • Now you can implement an is_logged_in property that retrieves the session key for a user from its profile model and then checks if the session is still valid by getting the session from the Session model. If it's valid, the user is logged in.

You can use the query to get user that you want to check is_logged_in or not.

def checkLoginStatus(username):
    
    if User.objects.filter(username=username).exists():
        usr = User.objects.get(username=username)
        if usr.is_authenticated:
            return True
        else:
            return False
    else:
        print("No user exist with this {} username.".format(username))
        return False
Related