Django: is_authenticated and is_anonymous both return true after logout

mgPePe picture mgPePe · Nov 28, 2010 · Viewed 7.8k times · Source

I am using django-registration, and just set it up.

{{user.is_authenticated }}

is true, even though i went already to /accounts/logout/ and logged the user out.

{{user.is_anonymous }} 

returns true also. According to django docs, those two should be different:

is_anonymous: Always returns False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated() to this method.

and

is_authenticated: Always returns True. 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 - it only indicates that the user has provided a valid username and password.

I am using the standard views that come with django-registration and haven't touched them yet. In the tempalate i have the following code:

{% if user.is_authenticated %}
{% user }}
{% if user.is_anonymous %}
    is anonymous
{% endif $}
{% else %}
    gotta login
{% endif %}

Where would the problem be? I will be really thankful!

UPDATE: i have noticed that on the homepage, it both is_authenticated and id_anonymous return True, while if i go to /accounts/login before loging in, only is_anonymous returns true as it should be. And also, on the homepage, i have the following view if that helps:

def home(request):
    return render_jinja(request, 'index.html', blah = 'ga')

UPDATE 2: print(request.user.is_authenticated()) gives False. Then, i have:

return render_jinja(request, 'index.html', blah = 'ga')

and in the template, user.is_authenticated returns FALSE.

UPDATE 3: If i use render_to_response, instead of render_jinja, all is good. still don't know how to fix this though :(

Answer

istruble picture istruble · Nov 29, 2010

It seems like you are trying to figure out two things at once; what is the correct way to use jinja templates and what is the deal with User/AnonymousUser. Maybe try to figure out these problems one at a time.

I have no experience with jinja but you may want to check and make sure that you are taking differences between jinja and django template syntax into account. The biggest difference I know of is that a method call requires explicit parenthesis. So the is_authenticated and is_anonymous calls in your example need parenthesis.

Jinja style {{ user.is_authenticated() }}
Django style {{ user.is_authenticated }} 

If that does not solve the problem, try installing django-debug-toolbar and take a look at the context for your template. Check and see if user is None or an object (User or AnonymousUser).

You can also read up on AnonymousUser and see an example of checking for an authenticated user in the docs. In a nutshell, for an AnonymousUser object is_anonymous() always returns True instead of False and is_authenticated() always returns False instead of True.