我正在尝试登录用户,但出现属性错误。
这是我的 forms.py :
class Login(forms.Form):
email = forms.EmailField(max_length=250)
password = forms.CharField(widget=forms.PasswordInput)
def login_user(self):
email = self.cleaned_data['email']
password = self.cleaned_data.get('password')
user = authenticate(email=email, password=password)
if user in User.objects.all():
login(self, user)
else:
return render(self, 'todoapp/waiting_2.html')
这是我的 views.py :
def login_user(request):
if request.method == 'POST':
login_form = Login(request.POST)
if login_form.is_valid():
login_form.login_user()
login_form.save()
return HttpResponseRedirect(reverse('dashboard'))
else:
return render(request, 'todoapp/waiting_2.html')
return render(request, 'registration/login.html', {'form': Login()})
当我填写字段并尝试登录时,出现错误:
AttributeError at /login/
'Login' object has no attribute 'session'
跟踪:
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gblp250/PycharmProjects/assignment/todoapp/views.py" in login_user
48. login_form.login_user(request)
File "/home/gblp250/PycharmProjects/assignment/todoapp/forms.py" in login_user
27. login(self, request, user)
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
126. if SESSION_KEY in request.session:
Exception Type: AttributeError at /login/
Exception Value: 'Login' object has no attribute 'session'
答案 0 :(得分:3)
这里有一些错误。尝试以login_user方法形式呈现的主要方法之一。除了其他以外,您尝试将self
作为要渲染的请求参数,这毫无意义。
如果/其他都删除,则全部删除。您不需要渲染;但也请注意,您的if条件不必要地效率低下。如果您拥有用户,则一定是用户。
最后,是错误的实际原因,您再次尝试将self代替请求,但是这次将其作为login
的参数。该代码属于视图。
最后,该表单不是ModelForm,因此没有保存方法。
所以,形式:
def login_user(self):
email = self.cleaned_data['email']
password = self.cleaned_data.get('password')
return authenticate(email=email, password=password)
并查看:
if login_form.is_valid():
user = login_form.login_user()
if user:
login(request, user)
return HttpResponseRedirect(reverse('dashboard'))
尽管此时您也可以将所有逻辑移至视图。
答案 1 :(得分:0)
login()
将请求作为第一个参数,您以表单作为第一个参数来调用它。
https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.login