Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django custom login view -> Session not persistent

Environment: Django 1.9.6 Python 3.5

I've made a custom User Model for the user and permission management.

Now, I have a problem at my login view, which I do not understand.

def login_user(request):
    if request.POST:
        username    = request.POST['username']
        password    = request.POST['password']
        user        = authenticate(username=username, password=password)
        if user is not None:
            # User Object is fine...
            if user.is_active:
                login(request, user)
                # Login passes -> request.user is OK and request.session _session_cache is filled corretly.. 
                if 'next'  in request.POST.keys():
                    redirect_to_next = request.POST['next']
                else:
                    redirect_to_next = settings.LOGIN_REDIRECT_URL
                return HttpResponseRedirect('/auth/main/')

    redirect_to_next = request.GET.get('next','/')
    return render(request, 'authentication/login.html', {'form': LoginForm, 'next' : redirect_to_next} )

After I was redirected to another page, the session is deleted... And request.user = AnonymousUser.

Here's the output from the session variable after I called the login() method...

{print(request.session.__dict__)
'modified': True, '_SessionBase__session_key': 'bn8qxxxxx', 'serializer': <class 'django.core.signing.JSONSerializer'>, 'model': <class 'django.contrib.sessions.models.Session'>, 'accessed': True, '_session_cache': {'_auth_user_hash': 'f5fxxxxxx', '_auth_user_id': '3f5b3fd1-XXXXXX', '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend'}}

and then I was redirected to another page...

{print(request.session.__dict__)
{'modified': False, '_SessionBase__session_key': None, 'serializer': <class 'django.core.signing.JSONSerializer'>, 'accessed': False}

Can someone help me? Thanks BR

like image 405
Flo Avatar asked Jul 05 '26 07:07

Flo


1 Answers

Set SESSION_COOKIE_SECURE to False in settings.py

Following stack overflow link may help you, Session data lost after a HttpResponseRedirect

like image 50
Jisson Avatar answered Jul 07 '26 07:07

Jisson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!