Is there a way to pass in an Form Object in an authenticate method in django

Question:

I am trying to pass in an form object in an authenticate() method but it is saying there is no attribute for username and password. Is there a specific way I can authenticate this form or not. I have imported everything already from forms and auth.models

MY VIEWS.PY

def user_login(request):

    if request.method == 'POST':

        login_info = LoginForm(request.POST)
        
        

        user = authenticate(username = login_info.username, 
        password=login_info.password)

        

        if user:

            login(request,user)


            return HttpResponse(reversed('index'))

        else:
           return HttpResponse("Wrong")

    else:
        login_info = LoginForm()
    
    return render(request,"login.html",{'logininfo':login_info})
MY FORMS.PY
class LoginForm(forms.Form):
    username = forms.CharField(label = 'Your username')
    password = forms.CharField(label= "Don't tell any but us",widget=forms.PasswordInput())
    
    

IS there a different way

user = authenticate(username = login_info.username, password=login_info.password)
Asked By: JACOB

||

Answers:

The data in the form is available through the cleaned_data dictionary.

So your authenticate line would be:

user = authenticate(username=login_info.cleaned_data['username'], password=login_info.cleaned_data['password'])

However, cleaned_data is only available after you have validated your form. So your code should look like this:

login_info = LoginForm(request.POST)
if login_info.is_valid():
    user = authenticate(username=login_info.cleaned_data['username'], password=login_info.cleaned_data['password'])
    # rest of the code
else:
    return HttpResponse("Wrong") # or display the same form with the errors
Answered By: Shohan Dutta Roy