I tried to change password without the traditional way. Give old password and new password, update the old password. I used UpdateApiView.But i get the following error.
Django doesn't provide a DB representation for AnonymousUser
I tried passigng Authorization token in header using POST MAN. But Same error.
view.py
class ChangePassword(generics.UpdateAPIView):
serializer_class = serializers.ChangePasswordSerializer
model = models.Customer
def get_object(self, queryset=None):
obj = self.request.user
return obj
def update(self, request, *args, **kwargs):
self.object = self.get_object()
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
if not self.object.check_password(serializer.data.get("old_password")):
return Response({"old_password": ["Wrong password."]}, status=HTTP_400_BAD_REQUEST)
self.object.set_password(serializer.data.get("new_password"))
self.object.save()
return Response("Success.", status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
serializers.py
class ChangePasswordSerializer(serializers.Serializer):
old_password = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
urls.py
path('update_password', views.ChangePassword.as_view()),
EDIT: I added TokenAuthentication in settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
In views.py, i added authentication_classes = (TokenAuthentication, )
Now i got name 'TokenAuthentication' is not defined
I imported TokenAuthentication in views.py
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
But Django doesn't provide a DB representation for AnonymousUser.
Add the attribute authentication_classes = (TokenAuthentication, )
to ChangePassword view.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.