Skip to content
Advertisement

Invalid password format or unknown hashing algorithm in Django class based view

I want to create user by API view. But I get this problem:

enter image description here

serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password')

views.py

class UserRegistration(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

How can I solve this problem?

Advertisement

Answer

You should override serializer’s create() method to hash password before saving new user object. You can use set_password for this:

 class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password')

    def create(self, validated_data):
        user = User(
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

Otherwise User.password will be stared in DB without hashing which is not secure.

Also you can use create_user method which is calling set_password by defaut:

 class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password')

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)
Advertisement