简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM