Django DRF创建用户

时间:2018-05-06 20:45:23

标签: django django-models django-rest-framework

我正在尝试序列化CreateUserSerializer(ModelSerializer) 我的代码如下。我的问题是它只会创建User而不是UserProfile

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    """
    Many other attributes like display_name, dob, hometown, etc
    """

serializers.py

class CreateUserProfileSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create(
                validated_data['username'],
                validated_data['email'],
                validated_data['password'])
        user.save()
        user_profile = UserProfile(user=user)
        user_profile.save()
        return user_profile

在我看来,它如下......

api/views.py

class RegistrationAPI(GenericAPIView):
    serializer_class = CreateUserProfileSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserProfileSerializer(user, context=self.get_serializer_context()).data,

        })

如果你按照代码,响应将给我一个

  

" RelatedManager没有属性' pk'"

1 个答案:

答案 0 :(得分:0)

serializer.py更改为以下

class CreateUserProfileSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        UserProfile.objects.create(user=user)
        return user