Python 属性错误';LoginForm';对象没有属性';清理数据';通过邮件和密码进行登录
views.py models.py forms.py 为什么它不起作用? 回溯:Python 属性错误';LoginForm';对象没有属性';清理数据';通过邮件和密码进行登录,python,django,Python,Django,views.py models.py forms.py 为什么它不起作用? 回溯: AttributeError at /auth/ 'LoginForm' object has no attribute 'cleaned_data' Traceback: views.py in login_view user = form.authenticate_via_email() forms.py in authenticate_user email=self.cle
AttributeError at /auth/
'LoginForm' object has no attribute 'cleaned_data'
Traceback:
views.py in login_view
user = form.authenticate_via_email()
forms.py in authenticate_user
email=self.cleaned_data['email'],
在访问
已清理的\u数据
属性之前,您需要在表单上调用。is\u valid()
您的views.py中没有调用form.is\u valid()
。
此外,没有从POST数据填充表单,如果您的request.method
是POST
您还可以查看源代码:
方法中的属性调用了
self.cleaned_data
,并且full_clean()
。因此,您可以从中跟踪您的错误。您尚未调用表单。是否有效()。
为了访问form.u数据,应该首先进行表单验证。
仅当对表单调用Form.is\u valid()
时,才会执行表单验证,表单反过来会返回一个已验证的已清理的数据
另外,在request.POST
上,您的表单无法获取数据,因为为此,您需要使用request.POST
初始化表单,如
form = LoginForm(request.POST)
我猜想,最后一个render\u to\u response
之前的return语句也会引起一些错误
您可以阅读有关表单验证的更多信息请修复缩进。@vishes\u shell抱歉,已修复
class LoginForm(forms.Form):
email = forms.CharField()
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
def clean(self):
user = self.authenticate_via_email()
if not user:
raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
else:
self.user = user
return self.cleaned_data
def authenticate_user(self):
return authenticate(
email=self.cleaned_data['email'],
password=self.cleaned_data['password']
)
def authenticate_via_email(self):
"""
Authenticate user using email.
Returns user object if authenticated else None
"""
email = self.cleaned_data['email']
if email:
try:
user = User.objects.get(email__iexact=email)
if user.check_password(self.cleaned_data['password']):
return user
except ObjectDoesNotExist:
pass
return None
AttributeError at /auth/
'LoginForm' object has no attribute 'cleaned_data'
Traceback:
views.py in login_view
user = form.authenticate_via_email()
forms.py in authenticate_user
email=self.cleaned_data['email'],
form = LoginForm(request.POST)