332

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.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Rick
  • 16,612
  • 34
  • 110
  • 163
  • 1
    is_authenticated (both inside and outside templates) always returns True - regardless of whether the user is actually logged in or not. To truely identify if a user is logged in, the only solution seems to be to compare their last_seen date/time with the timeout – Tony Suffolk 66 Apr 07 '18 at 07:40

7 Answers7

640

Update for Django 1.10+

is_authenticated is now an attribute in Django 1.10.

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

NB: The method was removed in Django 2.0.

For Django 1.9 and older

is_authenticated is a function. You should call it 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.

user2226755
  • 12,494
  • 5
  • 50
  • 73
Brian Neal
  • 31,821
  • 7
  • 55
  • 59
  • oh ok.. thanks for the info, that makes sense then why it wasn't working, unless I missed something, it is really not clear about this in the django documentation – Rick Sep 05 '10 at 03:38
  • 3
    @Rick: I beg to differ with you. is_authenticated() is the second item listed in the *methods* section of class models.User. What may be confusing is that the *template language* does *not* use the trailing ()'s, so you might see something like {% if user.is_authenticated %}. You'll get an error if you put the ()'s in. (See http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.is_authenticated and http://docs.djangoproject.com/en/1.2/topics/templates/#variables) – Peter Rowell Sep 05 '10 at 12:44
  • 2
    @Peter, well they don't use () in the examples, I realize that I am sure they explained somewhere that its a method and how to do it properly, its just nice when an API uses real life syntax in it so that it can be quickly taken in by someone new to a project like Django, just a pet peeve I guess as I tend to skim through things but I realize I should have looked closer, thanks for the help – Rick Sep 07 '10 at 07:24
  • 4
    @Rick: I completely agree with you about real life syntax. I have heard the (what I consider) lame reasons they have for not using a "real" programming language for the template system, but that's what they did. You can choose to use Jinja2 (http://jinja.pocoo.org/2/) and it will give you full Python capabilities, but since the overwhelming majority of 3rd party apps use the Django system it is often hard to intermix them. Look at ExprTag (http://djangosnippets.org/snippets/9/) for a way to get expressions inside of Django templates. It works. – Peter Rowell Sep 08 '10 at 02:34
  • 3
    @Rick the documentation says different things for different version. Looks like for 1.10 it's no longer a method – yairchu Aug 25 '16 at 18:43
  • @yairchu that is good to know, if perhaps not what tripped up @Rick! – mmw Dec 02 '16 at 12:45
  • didn't know user object is available in template, I previously thought it was request.user – MinhajulAnwar Dec 27 '17 at 11:14
  • @minhajul If you have the `auth` template context processor enabled (it is by default) and you use `RequestContext` to render the template, you get `request` and `user` in the template context. See https://docs.djangoproject.com/en/1.8/topics/auth/default/#users – Brian Neal Jan 01 '18 at 04:39
  • andis_authenticated (both inside and outside templates) always returns True - regardless of whether the user is actually logged in or not. – Tony Suffolk 66 Apr 07 '18 at 07:38
  • @TonySuffolk66 what? – Brian Neal Apr 23 '18 at 13:25
  • @BrianNeal using ``user.is_authenticated`` will ALWAYS return True if the user has logged in at all. I don't know whether ``request.user`` is always that same as ``user`` in all cases. I know that when you call logoff the session data that ``request`` is derived from is cleared and request.user is set to Anonymous and at that point request.user.is_authenticated will be False. – Tony Suffolk 66 Apr 23 '18 at 22:13
  • @TonySuffolk66 What you are describing contradicts my experience with using `user` in a template and the auth context processor. If you are still having trouble you might want to open a separate question describing your problem. – Brian Neal Apr 26 '18 at 16:12
  • @BrianNeal - I am not having a problem - I never try to confirm the logged in (or not) in my views - I use loginrequired (decorator or Mixin) and have different views for logged in or not - but that is just me :-) – Tony Suffolk 66 Apr 27 '18 at 06:39
  • @TonySuffolk66 `user.is_authenticated` is very useful in templates when you want to show different things to authenticated vs non-authenticated users. Your claim that it always returns True would mean Django has a serious bug that no one else has noticed. Anyway... no use arguing about it here in the comments of an unrelated question. – Brian Neal Apr 27 '18 at 19:24
  • It isn't a 'serious bug' - it is a documented feature: https://docs.djangoproject.com/en/2.0/ref/contrib/auth/#attributes – Tony Suffolk 66 Apr 27 '18 at 22:02
  • @TonySuffolk66 I guess maybe we are talking past each other here. If you use the auth context processor and then access `{{ user }}` in your template, you are either going to get a real `User` instance, in which, yes, `.is_authenticated` will always return true, or you are going to get an `AnonymousUser` instance in which it will return false. https://docs.djangoproject.com/en/2.0/ref/templates/api/#django-contrib-auth-context-processors-auth I was referring to the combination of auth context processor and using `{{ user }}` in a template context. – Brian Neal May 01 '18 at 00:27
  • is there any way to optimize the way we check if a user is logged-in or not in each view separately? – brainLoop Oct 07 '18 at 09:31
  • what is the alternative for django 2.0+? – py_ios_dev Oct 15 '18 at 14:43
  • @py_ios_dev - https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated – Underoos Jul 05 '19 at 05:34
  • remove the () at the end, it is not a method or function it is an object. use this: current_user.is_authenticated – Dominic M. Mar 11 '20 at 03:53
  • 3
    for django 3+ if request.user.is_authenticated: – Ajay Kumar Nov 05 '20 at 07:31
60

Django 1.10+

Use an attribute, not a method:

if request.user.is_authenticated: # <-  no parentheses any more!
    # do something if the user is authenticated

The use of the method of the same name is deprecated in Django 2.0, and is no longer mentioned in the Django documentation.


Note that for Django 1.10 and 1.11, the value of the property is a CallableBool and not a boolean, which can cause some strange bugs. For example, I had a view that returned JSON
return HttpResponse(json.dumps({
    "is_authenticated": request.user.is_authenticated()
}), content_type='application/json') 

that after updated to the property request.user.is_authenticated was throwing the exception TypeError: Object of type 'CallableBool' is not JSON serializable. The solution was to use JsonResponse, which could handle the CallableBool object properly when serializing:

return JsonResponse({
    "is_authenticated": request.user.is_authenticated
})
Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
  • 1
    but is_authenticated (both inside and outside templates) always returns True for a real user (and False for an anonymous user) - regardless of whether the user is actually logged in or not. – Tony Suffolk 66 Apr 07 '18 at 07:37
  • That's okay because this method is used on `request.user`. Whether a user is logged in or not only matters in the context of the request, for example the browser session. – Mark Chackerian Apr 09 '18 at 00:48
  • Assuming the application correctly logs out users - I have seen some that don't. – Tony Suffolk 66 Apr 10 '18 at 21:50
31

Following block should work:

    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>       
    {% endif %}
Sopan
  • 644
  • 7
  • 13
  • 2
    but is_authenticated (both inside and outside templates) always returns True - regardless of whether the user is actually logged in or not. – Tony Suffolk 66 Apr 07 '18 at 07:37
  • The document says: Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance. – Sopan Apr 09 '18 at 17:27
  • So if you want to display - un-authenticated users as "Welcome Guest" and authenticate users as "Welcome .USERNAME" then following block in templates can work: {% if user.is_authenticated %}

    Welcome {{ user.username }} !!!

    {% else %}

    Welcome Guest!!!

    {% endif %}
    – Sopan Apr 09 '18 at 17:29
10

In your view:

{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}

In you controller functions add decorator:

from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):
Cubiczx
  • 1,005
  • 11
  • 10
6

If you want to check for authenticated users in your template then:

{% if user.is_authenticated %}
    <p>Authenticated user</p>
{% else %}
    <!-- Do something which you want to do with unauthenticated user -->
{% endif %}
Suyash Kumar
  • 113
  • 1
  • 8
-2

to check if user is logged-in (authenticated user) in views.py file, use "is_authenticated" method, as the following example:

def login(request):
    if request.user.is_authenticated:
        print('yes the user is logged-in')
    else:
        print('no the user is not logged-in')

to check if user is logged-in (authenticated user) in your html templates file you can use it also as the following example :

 {% if user.is_authenticated %}
    Welcome,{{request.user.first_name}}           

 {% endif %}

this is just example , and change it based on your requirements.

i hope this helpful for you .

K.A
  • 1,399
  • 12
  • 24
-6

For Django 2.0+ versions use:

    if request.auth:
       # Only for authenticated users.

For more info visit https://www.django-rest-framework.org/api-guide/requests/#auth

request.user.is_authenticated() has been removed in Django 2.0+ versions.

Jatin Goyal
  • 487
  • 1
  • 4
  • 11
  • 8
    `request.user.is_authenticated` is still valid. You are referencing django-rest-framework documentation not [django](https://docs.djangoproject.com/en/2.1/topics/auth/default/#limiting-access-to-logged-in-users) – grouchoboy Feb 27 '19 at 11:26