2
votes

This is the content of views.py:


    @login_required
    def home_page(request):
        return HttpResponse("hello " + str(request.user))

    def login(request):
        return render(request, 'login.html')

    def verify(request):
        u = request.POST['username']
        p = request.POST['password']
        user = authenticate(username=u, password=p)
        if user is not None:
            if user.is_active:
                login(request)
                print("logged in")
                return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect('/accounts/login/')

On going to "/" I'm redirected to "/accounts/login" which take me to the login page. After I enter the username and password, in "Verify" the print statement printd "logged in" to the terminal.

So far so good. Now Instead of being redirected to "/", I'm being redirected to "/accounts/login" again and am being shown the page to enter username and password again. Why?


    [09/Jan/2015 10:50:14] "GET / HTTP/1.1" 302 0
    [09/Jan/2015 10:50:14] "GET /accounts/login/?next=/ HTTP/1.1" 200 250
    logged in
    [09/Jan/2015 10:50:19] "POST /accounts/verify/ HTTP/1.1" 302 0
    [09/Jan/2015 10:50:19] "GET / HTTP/1.1" 302 0
    [09/Jan/2015 10:50:19] "GET /accounts/login/?next=/ HTTP/1.1" 200 250

1

1 Answers

4
votes

You're forgetting the second argument to login which is the user object. This is causing the login to fail, so when you redirect to the front page (which has @login_required), you are sent back to the login form to "log in again". Look at the docs.

Edit: You are both importing django.contrib.auth.login and having a function in your script called login -- these names collide and your locally defined function "takes over". You should rename your local function (I call it login_view below), or import the login function as a qualified/different name (You could, for example, do from django.contrib.auth import authenticate, login as login_user)

from django.contrib.auth import authenticate, login

@login_required
def home_page(request):
    return HttpResponse("hello " + str(request.user))

def login_view(request):
    return render(request, 'login.html')

def verify(request):
    u = request.POST['username']
    p = request.POST['password']
    user = authenticate(username=u, password=p)
    if user is not None:
        if user.is_active:
            # You need to call `login` with `request` AND `user`
            login(request, user)
            print("logged in")
            return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/accounts/login/')