Santosh Ghimire
Santosh Ghimire

Reputation: 3145

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?

Upvotes: 3

Views: 16641

Answers (2)

akshat dokania
akshat dokania

Reputation: 1

This is from django documentation. You seem to not have passed the request in ...authenticate(request, user...)

This example shows how you might use both authenticate() and login():

    from django.contrib.auth import authenticate, login

    def my_view(request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            # Redirect to a success page.
            ...
        else:
            # Return an 'invalid login' error message.
            ...

Upvotes: 0

Paul
Paul

Reputation: 1056

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.

Upvotes: 12

Related Questions