dimanche 31 juillet 2016

Django authenticate not keeping user logged in

I am attempting to learn Django's authentication system by contriving a basic login scenario. My views are set up such that a view, logIn, either receives a user's credentials (and prints the success/failure of the login), or it renders a login form.

A second view, privatePage, is designed as a sanity check that the user is actually logged in. The code is as follows:

views.py:

@login_required(login_url='/logIn')
def privatePage(request):
    return HttpResponse("You're viewing a private page")

@csrf_exempt
def logIn(request):
    if request.method == "POST" and \
       request.POST.get('email') and \
       request.POST.get('password'):
        user = authenticate(username=request.POST['email'], 
                            password=request.POST['password'])
        return HttpResponse('Valid login' if user is not None else 'Invalid login')
    # render login form
    return HttpResponse("<form>...</form>")

I'm finding that after succcessfully logging in via the logIn view, I am still redirected to the login view upon trying to visit privatePage. FYI, I'm attempting to visit the privatePage view directly by URL, as opposed to navigating through provided links (e.g. I'm not sure if I'm violating some CSRF rule).

Any idea what's going on?




Aucun commentaire:

Enregistrer un commentaire