Home > OS >  Cannot assign "...'": "TestData.user" must be a "User" instance
Cannot assign "...'": "TestData.user" must be a "User" instance

Time:09-27

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.

CodePudding user response:

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)

CodePudding user response:

You mentioned that you are using an auth token. Try verifying in your view testDataApi if request.user was correctly set with an auth.User object. Try logging it with something like below to make sure that it is correctly set to the user for the provided token:

@csrf_exempt
def testDataApi(request, id=0):
    print(type(request.user), request.user)  # Should display the user for the provided token.
    ...

If it isn't set, then you have to configure how it would correctly map an auth.User object from a provided token. You might want to look at the following:

  • Related