pythondjangodjango-viewsdjango-authenticationdjango-users

Django.auth.authenticate not authenticating user


I am creating an app, and I am trying to manually create the login page so I can add some things that I can't add using the default Django authentication pages. This is what my view looks like:

def logIn(request):
    formClass = LogInForm
    template = "login.html"
    
    if request.method == "POST":
        auth.authenticate(username=request.POST["username"], password=request.POST["password"])
        return redirect("/")
    
    return render(request, template, {
        "form" : formClass
    })

But, when I print out the user's id after logging in, it returns none. Does somebody know what is going on?


Solution

  • authenticate only check usercredentails. For creating a user session you need to call login function. Import login function and modify the code like this.

    from django.contrib.auth import authenticate, login
    
    def logIn(request):
        formClass = LogInForm
        template = "login.html"
        
        if request.method == "POST":
            user  = auth.authenticate(username=request.POST["username"], password=request.POST["password"])
            if user:
                login(request, user)
                return redirect("/")
        
        return render(request, template, {
            "form" : formClass
        })