Skip to content Skip to sidebar Skip to footer

Writable Nested Serializers User And User Profile Doesn't Work

I'm trying to create a user registration endpoint through django rest framework with his profile and it shows me that I have not created an explicit .create() method for my seriali

Solution 1:

Your code looks OK, but your indentation looks wrong: the .create() method needs to be a method on the serializer, so it should be indented to the same level as the class Meta: statement.

It should probably look like this (note the indent on the create() method):

class UserSerializer(serializers.ModelSerializer):

    profile = ProfileCreateSerializer()

    class Meta:
        model = User
        fields = [ 'username', 'profile', ]

    def create (self, validated_data):
        user = User.objects.create(username=validated_data['username'])
        user.set_password(User.objects.make_random_password())
        profile_data = validated_data.pop('profile')
        Profile.objects.create(user=user, **profile_data)
        user.save()

More examples at DRF Docs (Saving Instances), in case that helps.

Post a Comment for "Writable Nested Serializers User And User Profile Doesn't Work"