Reputation: 649
This is following on from my other question, as it will likely require a different answer.
The code in my template is always returning false:
{% if request.user.is_authenticated %}
<p>I'm logged in</p>
{% else %}
<p>I am anonymous</p>
{% endif %}
I understand from the docs that I need to include "django.contrib.auth.context_processors.auth" within TEMPLATE_CONTEXT_PROCESSORS
in settings.py so I have done so as follows:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.contrib.auth.context_processors.auth", #Added
)
As for my views.py, I am using the render_to_response()
but feel this may be causing the issue. I also need to pass a user from the database within the context, but have added the third parameter context_instance=RequestContext(request)
def public_profile(request, username_in_url):
user = User.objects.get(username = username_in_url)
context = {
'user': user,
}
return render_to_response('public_profile.html', context, context_instance=RequestContext(request))
Why does request.user.is_authenticated
still return false even though a user is logged in? Using the same method within views.py works correctly e.g.
if request.user.is_authenticated():
return render_to_response('public_profile.html', context)
else:
return render_to_response('public_profile_anon.html', context)
Upvotes: 1
Views: 1993
Reputation: 151401
The documentation for django.contrib.auth.context_processors.auth
says that this context processor defines two variables: user
and perms
. And user
is
An
auth.User
instance representing the currently logged-in user (or anAnonymousUser
instance, if the client isn’t logged in).
So although in your Python code you would access request.user
to perform your check, in the template it is user
.
The problem with your specific case is that you also pass a dictionary that defines user
on the basis of username_in_url
. This clashes with the variable defined by django.contrib.auth.context_processors.auth
.
So:
Change the dictionary (which you named context
) so that user
has a different name. (And change references to it in your template.)
Change your template to check {% if user.is_authenticated %}
.
Upvotes: 6