Home > front end >  Simple password login/logout using django and session storage. Stay logged in not working
Simple password login/logout using django and session storage. Stay logged in not working

Time:07-17

I am trying to make a password protected page in a website using django. There is no need for any username, just a user to enter a password to gain access. That's fine, but I've got a checkbox so that they can choose to stay logged in for the session, but then on the actual protected page itself, a logout button should they wish to. My idea is to set a session variable when submitting the log in form if the box is checked, check for that variable at the start of the function to go straight to the page if it exists on revisiting and to delete the variable and return to login page if logout is pressed.
However I can't make it work, I am trying all sorts of syntaxes.. does it want the session variable to be a dictionary?
I'm quite a novice and not very good at knowing syntax. If someone could look at my functions and help I'd be very grateful.


def investors(request):
    """ A view show the investor login page (or investors page if a correct password is in session) and load the investors page if a correct password is entered. Also set a session variable that staylogged is ture if the stay logged in box is checked"""

    if request.session.get(['staylogged'] == True):

        return render(request, 'home/investors.html')
    else:
        if (request.method == 'POST'):
            password = request.POST.get("password")
            staylogged = request.POST.get("staylogged")
            if (password == os.environ.get('INVESTOR_PASSWORD')):
                if staylogged:
                    request.session['staylogged'] = {
                        'staylogged': True
                        }
                return render(request, 'home/investors.html')
            else:
                return redirect('investorerror')

        return render(request, 'home/investorlogin.html')


def logout(request):
    """A view to change the staylogged in session variable to false and return to the login page"""
    request.session['staylogged'] = {
        'staylogged':False
    }
    return redirect('investors')

CodePudding user response:

The reason that your stay_logged check isn't working is because the GET.get() is not just getting the dict but also checking == True for some reason. See my adjustments below:

if request.session.get('staylogged').get('staylogged') == True:

The reason why I have two .gets is because your staylogged session value is a dict within the session dict, which I would suggest removing.

  • Related