Password Validation Not Work In Django-rest-framework
when I register new user at that time password validator not work.(e.g. When I enter admin123 and password is also admin123 at that time password validator not saw like this error:
Solution 1:
The second argument of validate_password
is User object, not username string.
You can see that in docs here: https://docs.djangoproject.com/en/3.1/topics/auth/passwords/#django.contrib.auth.password_validation.validate_password
Try this in your views.py
:
from rest_framework import status
from django.contrib.auth import get_user_model
from .serializers import SignUpSerializer
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
User = get_user_model()
@api_view(['POST'])@permission_classes([AllowAny,])defsignup(request):
serializer = SignUpSerializer(data=request.data)
if serializer.is_valid():
username = serializer.data['username']
user = User(
username = username,
email = serializer.data['email']
)
try:
validate_password(serializer.data['password'], user)
except ValidationError as e:
return Response(str(e), status=status.HTTP_400_BAD_REQUEST)
user.set_password(serializer.data['password'])
user.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Post a Comment for "Password Validation Not Work In Django-rest-framework"