[英]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.我试图在 authenticate() 方法中传递一个表格 object 但它说没有用户名和密码的属性。 Is there a specific way I can authenticate this form or not.
是否有特定的方法可以验证此表单。 I have imported everything already from forms and auth.models
我已经从 forms 和 auth.models 导入了所有内容
MY VIEWS.PY
我的观点.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.表单中的数据可通过
cleaned_data
字典获得。
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.但是,
cleaned_data
仅在您验证表单后可用。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.