How to make a serializer to register a user with a password verification field.

class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}) password2 = serializers.CharField(style={'input_type': 'password'}) class Meta: model = ExtUser fields = ('email', 'name', 'password', 'password2') extra_kwargs = {'password': {'write_only': True, }, 'password2': {'write_only': True, }, } def validate(self, attrs): data = super(UserSerializer, self).validate(attrs) if data['password'] != data['password2']: raise serializers.ValidationError('Password mismatch') del data['password2'] return data def create(self, validated_data): user = ExtUser( email=validated_data['email'], name=validated_data['name'], ) user.set_password(validated_data['password']) user.save() return user def update(self, user, validated_data): user.name = validated_data['name'] user.set_password(validated_data['password']) user.save() return user 

in the tests produces such an error

AttributeError: Got AttributeError when trying to get a value for the field password2 on the serializer UserSerializer . This could be a ExtUser Original exception text was: 'ExtUser' object has no attribute 'password2'.

    1 answer 1

    It is necessary to remove the password and password2 fields from Meta.fields . You use the ModelSerializer , which maps the model fields to what is specified in Meta.fields . You can remove extra_kwargs , because these fields are set in the current class and not generated.

     class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, style={'input_type': 'password'}) password2 = serializers.CharField(write_only=True, style={'input_type': 'password'}) class Meta: model = ExtUser fields = ('email', 'name', 'password')