Vikram
Vikram

Reputation: 7515

Session expiring when reloading page in django auth

Whenever I reload my page clicking enter in the adresss bar URL of browser or opening the same URL in another tab, the session seems to be expired. I mean my page is navigating to Login Page.

Here is my view. The below view will render in one HTML page which is index.html. Whenever a user login's Username/Password login form is displayed other wise it says thank you for login. So this functionality is working fine.

def index(request):
     if request.user.is_authenticated():
            return HttpResponseRedirect('/myapp/')

     if request.method == 'POST':
            form = UserLoginForm(request.POST)
            if form.is_valid():
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
            if request.user.is_authenticated():
                return HttpResponseRedirect('/myapp/')
            else:
                user = authenticate(username = username, password = password)
            return shortcuts.render_to_response('index.html',locals(),
                                    context_instance = context.RequestContext(request))
     else:
            form = UserLoginForm

return shortcuts.render_to_response('index.html',locals(),
                                    context_instance = context.RequestContext(request))

For your reference I have installed below middle ware classes in my app.

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',

Can some one help me on this please

-Ram

Upvotes: 0

Views: 1451

Answers (2)

thikonom
thikonom

Reputation: 4267

Add a call to the login function because this function is responsible for saving the user's ID in the session, like so:

else:
    user = authenticate(username = username, password = password)
    if user is not None:
        login(request, user)
    else:
        ...

Upvotes: 1

Rajat Saxena
Rajat Saxena

Reputation: 3925

That's because you're using 'authenticate' method and not 'login' method.What you're trying to do will be accomplished by using 'login' instead of 'authenticate'.When you use 'login',it saves user's ID in the session.See this https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.login

Upvotes: 1

Related Questions