Philipp K
Philipp K

Reputation: 333

Data gets lost when being passed to serializer

I am trying to update the information field on my Profile model. The endpoint is receiving the data correctly, but it seems like the serializer does not get the data. I don't understand why and none of my attempts to fix it have worked.

Model:

class Profile(models.Model):
    id = models.UUIDField(uuid.uuid4, primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
    information = models.JSONField(null=True)
    

    def __str__(self):
        return f'{self.user} Profile'

Endpoint:

class ProfileView(viewsets.ModelViewSet):
    serializer_class = ProfileSerializer
    queryset = Profile.objects.all()

    def update(self, request, *args, **kwargs):
        # Retrieve the user's profile
        profile = Profile.objects.get(user=request.user)
        # Update the information field with the data from the request
        data = request.data
        print(data) # This prints the data correctly
        serializer = self.get_serializer(profile, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

Serializer:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ["user", "information"]
    
    def validate(self, attrs):
        print(attrs) # this prints an empty OrderedDict
        return super().validate(attrs)
    
    def update(self, instance, validated_data):
        print(validated_data) # This prints an empty dictionary
        # Update the information field with the data from the request
        instance.information = validated_data["information"]
        instance.save()
        return instance

The data i'm passing through the request body:

JSON.stringify({"information": {"name": "xxx", "birthday": "xxx}})

How is it possible that the data just vanishes? Any help is very appreciated

Upvotes: 0

Views: 384

Answers (1)

Philipp K
Philipp K

Reputation: 333

Ok, I'm an idiot and forgot to set "Content-Type": "application/json" in my request header. Hopefully it will save someone else time.

Upvotes: 1

Related Questions