How to Check if a User is Logged In or Not in Django



Python


In this article, we go over how to check if a user is logged in or not in Django.

So, there's a few ways of doing this, but the way we will go over is by using the request object in Django.

By calling request.user, we are able to access the user that is currently logged in.

We then can use the is_authenticated property to determine if a user is currently authenticated (logged into the account).

So, we'll create a simple script that if a user is logged in, we will print, "Logged in", and if a user is not logged in, we will print out, "Not logged in"

Basically, we do this all in the views.py file, which is the file where our main Python code always goes.

The code is shown below.



So in this code, in our views.py file, we have a function called index, which is passed in the argument,. request.

request.user references the user that is logged in (or not if not logged in). The property, is_authenticated, then checks to see if the user is authenticated (logged in).

If so, we print out, "Logged in". If not, we print out, "Not logged in".

Of course, there are many other things you could do besides just print out these statements.

If a user is logged in, we could render a template. If no one is logged in, we could render another template.

Other things, we could do is if a user is logged in, we could render a template. If not, we could raise a 404 Page Not Found Error.

Another thing we could do is if a user is logged in, we could render a template. If not, we could redirect the user to the login page.

So there are several things that could be done based on whether a user is logged in or not.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...