MS25
MS25

Reputation: 1

django rest framework POST error. When I send a JSON/dictionary inside a Json it returns: "Not a valid string."

I'm trying to get this test API working, it is very simple and the model consist of only one class with 2 fields. My viewset inherits from ModelViewset and I added(to make it more explicit, and make some changes in the future) the list and create function. I could POST a few JSONs with succes, but when I try to post this one that has a 'nested json' it returns

 "Not a valid string."

Here is the code and the JSON:

views.py:

class SessionViewset(viewsets.ModelViewSet):
    """"
    A simple viewset for listing or retrieving 'sessions'
    """
    queryset = Session.objects.all()
    serializer_class = SessionSerializer

    def list(self, request):
        queryset = Session.objects.all()
        serializer = SessionSerializer(queryset, many=True)
        return Response(serializer.data)
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

JSON:

{
    "meta":"aca va la metadata",
    "reunion":{"juan":500,
            "pedro":300,
            "jose":1000}

}

and it returns:

{
    "reunion": [
        "Not a valid string."
    ]
}

screenshot: screenshot of the problem

models: models

serializers: serializers

Do you know if there is any limitation that I'm not aware of, or how can I solve this issue? Thanks

Tried to POST that JSON, into the API endpoint, with said error response

Upvotes: 0

Views: 386

Answers (1)

Sardar Faisal
Sardar Faisal

Reputation: 671

@MS25 as I mentioned in the comment your model has the reunion as CharField and you are sending an object data type to it.

If you still want to send the same data to the reunion then try something along the lines:

{
    "meta":"aca va la metadata",
    "reunion":JSON.stringify({"juan":500,
            "pedro":300,
            "jose":1000})
}

I am not sure of the results maybe it will work maybe not.

Upvotes: 0

Related Questions