django rest framework create user with password

后端 未结 4 777
说谎
说谎 2021-02-07 13:37

Using django-rest-framework 3 and django 1.8

I am trying to create a user using django-rest-framework ModelViewSerializer. problem is that the default objects.create m

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-07 13:56

    you can override create in UserSerilizer:

    class UserSerializer(serializers.ModelSerializer):
        # ....
    
        def create(self, validated_data):
            user = User.objects.create_user(**validated_data)
            return user
    

    other solutions can be overriding perform_create in ViewSet class or you can write your own create method in your viewset class

    class UserViewSet(viewsets.ModelViewSet): 
        def create(self, request, format=None):
            # create user here
            # do not call seriailzer.save()
    

    UPDATE: after @freethebees commented, overriding perform_create also works, so here is the code snippet:

    class UserViewSet(viewsets.ModelViewSet, mixins.CreateModelMixin): 
        def perform_create(self, serializer):
            # use User.objects.create_user to create user
            pass
    

    NOTE: this answer gives 3 solutions, choose the one you think it better fits your needs and your project's ecosystem

    NOTE 2 I personally prefer overriding create in UserViewSet (second code snippet) because there you can simply return your custom Response (for example return user profile after login)

提交回复
热议问题