integrate django password validators with django rest framework validate_password

前端 未结 4 1912
误落风尘
误落风尘 2020-12-08 15:35

I\'m trying to integrate django validators 1.9 with django rest framework serializers. But the serialized \'user\' (of django rest framework) is not compatible with the djan

4条回答
  •  不知归路
    2020-12-08 16:18

    Like you mentioned, when you validate the password in validate_password method using UserAttributeSimilarityValidator validator, you don't have the user object.

    What I suggest that instead of doing field-level validation, you shall perform object-level validation by implementing validate method on the serializer:

    import sys
    from django.core import exceptions
    import django.contrib.auth.password_validation as validators
    
    class RegisterUserSerializer(serializers.ModelSerializer):
    
         # rest of the code
    
         def validate(self, data):
             # here data has all the fields which have validated values
             # so we can create a User instance out of it
             user = User(**data)
    
             # get the password from the data
             password = data.get('password')
    
             errors = dict() 
             try:
                 # validate the password and catch the exception
                 validators.validate_password(password=password, user=User)
    
             # the exception raised here is different than serializers.ValidationError
             except exceptions.ValidationError as e:
                 errors['password'] = list(e.messages)
    
             if errors:
                 raise serializers.ValidationError(errors)
    
             return super(RegisterUserSerializer, self).validate(data)
    

提交回复
热议问题