gpt4 book ai didi

Django DRF 创建用户

转载 作者:行者123 更新时间:2023-12-05 03:05:52 45 4
gpt4 key购买 nike

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

模型.py

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

序列化器.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 has no attribute '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


关于Django DRF 创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204365/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com