Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import django.contrib.auth.password_validation as validators
  2. from rest_framework import serializers
  3.  
  4. class RegisterUserSerializer(serializers.ModelSerializer):
  5.  
  6. password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
  7.  
  8. class Meta:
  9. model = User
  10. fields = ('id', 'username', 'email, 'password')
  11.  
  12. def validate_password(self, data):
  13. # validators.validate_password(password=data, user=User)
  14. # return data
  15.  
  16. # here data has all the fields which have validated values
  17. # so we can create a User instance out of it
  18. user = User(**data)
  19.  
  20. # get the password from the data
  21. password = data.get('password')
  22.  
  23. errors = dict()
  24. try:
  25. # validate the password and catch the exception
  26. validators.validate_password(password=password, user=user)
  27.  
  28. # the exception raised here is different than serializers.ValidationError
  29. except exceptions.ValidationError as e:
  30. errors['password'] = list(e.messages)
  31.  
  32. if errors:
  33. raise serializers.ValidationError(errors)
  34.  
  35. return super(RegisterUserSerializer, self).validate(data)
  36.  
  37. def create(self, validated_data):
  38. user = User.objects.create_user(**validated_data)
  39. user.is_active = False
  40. user.save()
  41. return user
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement