I am trying to implement a user registration with password hashing.
The problem is that the password is saved raw (as it was typed).
For some reason, I think the create method in the serializer is not called.
Doesn't matter if I comment the method out or not comment it out, and try to register, same result - is saves the user to the database without hashing the password. It means that the code doesn't execute?
Views.py
class UserViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsCreationOrIsAuthenticated,)
Serizliers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'password', )
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(
first_name=validated_data['first_name'],
username=validated_data['username'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
return user
I have been struggling with this for a while - can't has the password.
Any ideas?
Instead of writing your
createmethod inserializers.py, do this work by overriding theperform_create()method in yourviews.py. To do some extra work on creation of an object, DRF provides this hook. This will make the code more clean and DRY.As per the DRF docs,
You can do that by:
views.py