Reputation: 43
I am trying to serialize a CreateUserSerializer(ModelSerializer)
My code is as follows. My problem is that it will only create a User
and not a 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
And in my views it goes as follows...
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,
})
If you follow the code, the Response will give me a
"RelatedManager has no attribute 'pk'"
Upvotes: 4
Views: 7042
Reputation: 88669
Change your serializer.py
as below
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
Upvotes: 5