Search code examples
pythondjangodjango-authentication

authenticate() function not working django.contrib.auth


I have a login_page function and in this function the authenticate() function returns a user object only if it is a superuser. For normal user, it returns None. Which is not as the documentation says.

def login_page(request):
    if request.user.is_authenticated(): # if user is already logged in
        return HttpResponseRedirect('/') # SHOULD BE DASHBOARD
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            seo_specialist = authenticate(username=username, password=password) #returns None
            if seo_specialist is not None:
                login(request, seo_specialist)
                return HttpResponseRedirect('/') # SHOULD BE DASHBOARD
            else:
                return render(request, 'login.html', {'form': form})
        else:
            return render(request, 'login.html', {'form': form})
    else: 
        form = LoginForm()
        context = {'form': form}
        return render(request, 'login.html', context)

Is there anything wrong with my code?


Solution

  • Try this:

    def login_page(request):
        if request.method == "POST":
            username = request.POST['username']
            password = request.POST['password']
            seo_specialist = authenticate(username=username, password=password)
            if seo_specialist is not None:
                return HttpResponse("Signed in")
            else:
                return HttpResponse("Not signed in")
        else:
            # takes you to sign in form. 
    

    Basically replace is_valid and cleaned_data with request.POST and then authenticate. Also make sure you have

    from django.contrib.auth import authenticate

    at the top of your views.