send put request to http://127.0.0.1:8000/api/update_password/ with old and new password
new password failed validation
old password not match
pass
login
success
#api/serializer
from rest_framework import serializers
from django.contrib.auth.password_validation import validate_password
class PasswordSerializer(serializers.Serializer):
old_password = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
def validate_new_password(self, value):
validate_password(value)
return value
-----------------------------------------
#api/apiview
from music.api.serializers import PasswordSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
class UpdatePassword(APIView):
def get_object(self, queryset=None):
return self.request.user
def put(self, request, *args, **kwargs):
currentUser = self.get_object()
serializer = PasswordSerializer(data=request.data)
if serializer.is_valid():
# Check old password
old_password = serializer.data.get("old_password")
if not currentUser.check_password(old_password):
return Response({"old_password": ["Wrong password."]},
status=status.HTTP_400_BAD_REQUEST)
# set_password also hashes the password that the user will get
currentUser.set_password(serializer.data.get("new_password"))
currentUser.save()
return Response(status=status.HTTP_204_NO_CONTENT)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
--------------------------------
#api/urls
from django.urls import path
from music.api import apiview
from rest_framework.authtoken import views
app_name = 'musicAPI'
urlpatterns = [
path('api-token-auth/', views.obtain_auth_token, name='AuthToken'),
path('update_password/', apiview.UpdatePassword.as_view(), name='UpdatePassword'),
]
reference:
https://stackoverflow.com/questions/38845051/how-to-update-user-password-in-django-rest-framework
No comments:
Post a Comment