How to check if a user is logged in (how to properly use user.is_authenticated)?

ghz 1years ago ⋅ 7752 views

Question

I am looking over this website but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying:

request.user.is_authenticated

despite being sure that the user is logged in, it returns just:

>

I'm able to do other requests (from the first section in the url above), such as:

request.user.is_active

which returns a successful response.


Answer

Update for Django 2.0 and later

is_authenticated is an attribute

if request.user.is_authenticated:
    # do something if the user is authenticated

For Django 1.9 and older

is_authenticated() was a function. Called like:

if request.user.is_authenticated():
    # do something if the user is authenticated

As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:

{% if user.is_authenticated %}

However, in Python code, it is indeed a method in the User class.

NB: The method was removed in Django 2.0.