Django DRF create user



我正在尝试序列化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,
})

如果您遵循代码,响应会给我一个

"相关管理器没有属性'pk'">

按如下
方式更改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


最新更新