Is_authenticated returns True for AnonymousUser

I struggle with is_authenticated returning True when I have not logged in:

 u = request.user if u.is_authenticated: raise Exception('I am said to be authenticated, but I really am not.') 

To clarify, the Django debug view correctly identifies u as AnonymousUser :

 u <django.contrib.auth.models.AnonymousUser object at 0x9e76f4cc> 

Even stranger, inside the is_anonymous template is_anonymous fine:

 {% if not request.user.is_authenticated %} We are anonymous. {% endif %} 

Why is this?

+4
source share
2 answers

This is a method, not a property. You should call him:

 if u.is_authenticated(): 

Of course, in a template, Django automatically calls methods for you .

+24
source

is_authenticated is a method, so you need some parentheses. Otherwise, u.is_authenticated is a function object that is a True ish value.

In the template language, functions without arguments are evaluated as functions, so why are you good there.

+6
source

All Articles