繁体   English   中英

有没有办法在 django 的验证方法中传递表格 Object

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

我试图在 authenticate() 方法中传递一个表格 object 但它说没有用户名和密码的属性。 是否有特定的方法可以验证此表单。 我已经从 forms 和 auth.models 导入了所有内容

我的观点.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())
    
    

有不同的方法吗

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

表单中的数据可通过cleaned_data字典获得。

因此,您的身份验证行将是:

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

但是, cleaned_data仅在您验证表单后可用。 所以你的代码应该是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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