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

Issue

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:

Model

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)

Serializer

class TestDataSerializer(serializers.ModelSerializer):

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

View

@csrf_exempt
def testDataApi(request, id=0):
if request.method == 'GET':
    testdata = TestData.objects.all()
    testdata_serializer = TestDataSerializer(testdata,many=True)
    return JsonResponse(testdata_serializer.data,safe=False)
elif request.method == 'POST':
    testdata_data=JSONParser().parse(request)
    testdata_serializer=TestDataSerializer(data=testdata_data)
    if testdata_serializer.is_valid():
        testdata_serializer.save(user=request.user)
        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 testdata_serializer.save(user=request.user) back to testdata_serializer.save(), but I want the table to require a user’s id.

Appreciate any help, thank you.

Solution

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

views.py

from rest_framework.viewsets import ModelViewSet

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

serializers.py

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
        instance.save()

        # 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