Right way to check authenticated user in Django
I’m assuming that you’ve added these two middlewares in your settings.py as follows:
MIDDLEWARE_CLASSES = (
... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', )
Then you’ll be able to user object using request object like this: user = request.user
If you want to check whether the user is authenticated or not, then the wrong way to do this:
# Do not use
if request.user:
This will be true for both authenticated and anonymous user
Because request.user is not None or empty.
You can check this following any one of the two ways:
if request.user.id:
// recommended
if request.user.is_authenticated():