NotImplementedError:Django不提供数据库表示

时间:2015-09-04 10:03:07

标签: python django django-views django-orm

我收到以下错误:

Internal Server Error: /api/user/change-password/
Traceback (most recent call last):
 File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 132, in get_response
   response = wrapped_callback(request, *callback_args, **callback_kwargs)
 File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 71, in view
   return self.dispatch(request, *args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 89, in dispatch
   return handler(request, *args, **kwargs)

 File "/opt/project/views.py", line 227, in put
   request.user.set_password(password)
 File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 480, in set_password
   raise NotImplementedError("Django doesn't provide a DB representation for User.")
NotImplementedError: Django doesn't provide a DB representation for User.

我的代码显示在第227行:

class ChangePasswordAPI(View):
    @staticmethod
    def put(request):
        data = request.read()
        payload = json.loads(data)
        password = payload['password']

        if not request.user:
            return HttpResponse(
                json.dumps({
                    'success': False,
                    'error': 'user_not_exist'
                })
            )
        # the following line is 227
        request.user.set_password(password)
        request.user.save()

        return HttpResponse(
            json.dumps({
                'success': True,
            })
        )

首先,我认为这是因为我没有更新Django,但现在我有了,我收到同样的错误。

我查看了其他用户提出的一些解决方案,但没有在我的案例中应用

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

if not request.user:

这个if语句只检查request.user是否是一个真正的真实对象。如果用户未经过身份验证,则它是AnonymousUser,它没有数据库表示。 set_password()和其他各种方法会引发NotImplementedError

要解决此问题,请将if语句更改为:

if not request.user.is_authenticated():