简体   繁体   中英

Django , remembering that a user is logged in

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?

ps sorry for my bad english

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/ ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM