Reputation: 2907
So , I want to show logged/not logged users different menus.
If user isn't logged in: (Login , Register)
If he is already logged in: (Main , My profile , Logout)
views.py:
@csrf_protect
def loginn(request):
c = {}
c.update(csrf(request))
return render_to_response("login/login.html",c)
@csrf_protect
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return render_to_response('login/loggedin.html',RequestContext(request))
else:
return HttpResponseRedirect('/posts/invalid')
and template:
{% block Menu %}
{% if not request.user.is_authenticated %}
<li> <a href="/posts/login">Login</a> </li>
<li> <a href="/posts/register/">Register</a></li>
{% endif %}
{% if request.user.is_authenticated %}
<li><a href="/posts">Main</a></li>
<li><a href="#">My profile</a></li>
<li><a href="/posts/logout">logout</a></li>
{% endif %}
{% endblock %}
When in my LogIn page I click on Submit , on next page it works perfectly. There is Menu option for logged in users. But then , whatever I'll do (refresh page , go to main page ,etc) I'll see Menu option for not logged in users.
I've read django documentation for user authentication and now I know
that {% if user.is_authenticated %}
in templates works only with RequestContext
and If I get it right , there is no way to do what I want this way.
I want Django to remember that user is logged in all time regardless of what I'm doing (refreshing page , clicking links ,etc) Is there any way to do this in Django?
So how can I remember that a user has logged in and use it in template?
Maybe there is another way to remember that user is logged in and use it in template? Something with sessions, cookis , etc?
p.s. sorry for my bad english
Upvotes: 0
Views: 956
Reputation: 77892
First point: to make sure you have your context processors working, you have to use a RequestContext
in all your views. The simplest way is to use the render()
shortcut (https://docs.djangoproject.com/en/1.6/topics/http/shortcuts/#render) instead of render_to_response()
.
Second point: HTTP is a stateless protocol, so for your app to remember anything between requests, you need session support. From what you describe, I strongly suspect you forgot to enable the SessionMiddleware (cf https://docs.djangoproject.com/en/1.6/topics/auth/).
Upvotes: 2