2

It drives me crazy... I read tons of posts about how to hash your password when creating a user, but for some reason is just won't work and I can't authenticate.

I am using django 1.8.1 and django-rest-framework 3.1.2

My code:

views.py:

class UserViewSet(mixins.CreateModelMixin,
               mixins.RetrieveModelMixin,
               mixins.ListModelMixin,
               viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticated, )

----EDIT----

With this code, the password appears as is in the database and is not hashed, so I can't authenticate.

serializers.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

And also - what method does serializer.save() call??

Any idea??? any help would be appreciated!

1 Answer 1

1

Serializers don't have a post_save method, not even before v3. You must be confused with the post_save in generic views. The generic view's pre_save and post_save hooks no longer exist, but are replaced with perform_create and perform_update.

You just need to do obj.set_password in user serializer's create method. There's an example in the docs that does exactly what you're looking for.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks I'll try it. And do I leave the create method in the UserViewSet as is? And also, what method exactly does serializer.save() call?
You can actually remove the create method in your viewset. serializer.save() knows when to call the serializer's update method or create method.
But doesn't the url being translated into a view? I mean, without the create method in the ViewSet how will it know to call the serializer.save()? Just trying to understand the whole thing..
You're using the CreateModelMixin which implements creating and saving a new model instance.
I tried the piece of code from the docs - it is not hashing the password, it appears as is in the database. I think I don't even get to the serializer code (when I put breakpoints in the create method, it doesn't get there). also checked and with or without the create method in the serializer makes no difference in the database, so the create code doesn't execute. ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.