我收到以下错误:
Traceback:
File "C:\Users\HP\GST\lib\site-packages\django\core\handlers\exception.py"
in inner
35. response = get_response(request)
File "C:\Users\HP\GST\lib\site-packages\django\core\handlers\base.py" in
_get_response
128. response = self.process_exception_by_middleware(e,
request)
File "C:\Users\HP\GST\lib\site-packages\django\core\handlers\base.py" in
_get_response
126. response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "C:\Users\HP\Desktop\erpcloud\accounts\views.py" in change_password
31. if form.is_valid():
File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in is_valid
179. return self.is_bound and not self.errors
File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in errors
174. self.full_clean()
File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in
full_clean
376. self._clean_fields()
File "C:\Users\HP\GST\lib\site-packages\django\forms\forms.py" in
_clean_fields
397. value = getattr(self, 'clean_%s' % name)()
File "C:\Users\HP\GST\lib\site-packages\django\contrib\auth\forms.py" in
clean_old_password
366. if not self.user.check_password(old_password):
File "C:\Users\HP\GST\lib\site-packages\django\contrib\auth\models.py" in
check_password
396. raise NotImplementedError("Django doesn't provide a DB
representation for AnonymousUser.")
Exception Type: NotImplementedError at /accounts/change-password/
Exception Value: Django doesn't provide a DB representation for
AnonymousUser.
我的视图如下:
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, user)
return redirect(reverse('company:Dashboard'))
else:
return redirect(reverse('accounts:change_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'accounts/change_password.html', args)
首先,我认为这是由于我没有更新Django,但现在我已经更新了,并且收到了相同的错误。
我查看了其他用户要求的一些解决方案,但没有一个适用于我的情况
有什么帮助吗?
答案 0 :(得分:4)
视图本身没有错。问题是,如果用户未登录,则request.user
将指向AnonymousUser
对象。您可以将其视为虚拟用户。但是,该用户没有数据库表示形式,因为我们对该用户一无所知。更多用于提供统一的界面。
现在,由于request.user
是AnonymousUser
,因此您打算更改该用户的密码,但是您无法将该密码存储到数据库中,因此会出现错误。
因此,首先用户需要登录,然后request.user
将是真实用户,并且更新密码应该可以。
但是我建议在视图中添加一个@login_required
装饰器,以防止发生这种情况:
from django.contrib.auth.decorators import login_required
@login_required
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, user)
return redirect(reverse('company:Dashboard'))
else:
return redirect(reverse('accounts:change_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'accounts/change_password.html', args)