Django - Object of type User is not JSON serializable

I am facing an issue with POSTing data (which has a User object) to a ModelViewSet. Error: "Object of type User is not JSON serializable"

data_params = {
        "log_user_id": user,
        "device_name": "sampledevice",
        "log_user_email": "svc.netadc@ads.aexp.com",
        "feature_name": 'Subnet Automation',
    }

    print(data_params, "data_params")
    response = requests.post("<url>/netadc3/arista/ImplementationLogsAristaViewSet/implementationlogsarista/",
    auth=(<username>, <password>), headers={"content-type": "application/json"}, data=json.dumps(data_params), verify=False)

serializers.py:

class ImplementationLogsAristaSerializer(serializers.HyperlinkedModelSerializer):

    log_user_id = UserSerializer(read_only=True)

    class Meta:
        model = ImplementationLogsArista
        fields = ('log_id','device_name', 'log_user_id','log_user_email','feature_name')

views.py:

class ImplementationLogsAristaViewSet(viewsets.ModelViewSet):
    queryset = ImplementationLogsArista.objects.all()
    serializer_class = ImplementationLogsAristaSerializer
    permission_classes = (IsAuthenticated,)
    pagination_class = None

Not sure how to successfully POST the data with User into the ModelViewSet.

Probably, your user is Django User model instance, which is not JSON serializable:

data_params = {
        "log_user_id": user, # <-- here
data=json.dumps(data_params) # <-- here 

You should put user.pk in data_params:

data_params = {
        "log_user_id": user.pk, # <-- here
Back to Top