Cannot assign "…'": "TestData.user" must be a "User" instance


Very new to the Django Rest Framework, so would appreciate some help with this one. I get the error in the title when I try and do a POST request in Postman with an appropriate auth token.

I’ve made a table that I want to send a POST request to, but having issues with getting a user FK to be accepted as one of the columns. Plz see model/serializer/view below:


class TestData (models.Model):
TestSDG = models.DecimalField(decimal_places=0, max_digits=2, default=0)
user = models.ForeignKey("auth.User", related_name="testdata", on_delete=models.CASCADE)


class TestDataSerializer(serializers.ModelSerializer):

class Meta:
    model = TestData
    fields = ('id', 'TestSDG')


def testDataApi(request, id=0):
if request.method == 'GET':
    testdata = TestData.objects.all()
    testdata_serializer = TestDataSerializer(testdata,many=True)
    return JsonResponse(,safe=False)
elif request.method == 'POST':
    if testdata_serializer.is_valid():
        return JsonResponse("Added Successfully", safe=False)

The POST request works fine if I don’t use the user as a foreign key, and I change back to, but I want the table to require a user’s id.

Appreciate any help, thank you.


You should be using a ModelViewset in your file – then you can override the update method on your serializer:

from rest_framework.viewsets import ModelViewSet

class TestDataViewSet(ModelViewSet):
    queryset = TestData.objects.all()
    serializer_class = TestDataSerializer

class TestDataSerializer(serializers.ModelSerializer):


    def update(self, instance, validated_data):

        # get user id from validated data:
        user_id = validated_data.pop('user_id')

        # get user:
        user = User.objects.get(id=user_id)

        # set user on instance:
        instance.user = user

        # continue with update method:
        super().update(instance, validated_data)

Answered By – Daniel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published