Django + React axios POST cant access Json properties

Viewed 38

I created two abjects that need to be treated separated in the backend, and sent it to backend with:

const order = {
    order_id: 1,
    customer: {
        name: "Jonas Illver"
        age: 18
    }
}

const car = {
    model: 'XHL'
    brand: 'Toyota'
}

const postData = {
    order: order,
    car: car
}

const res = await axios.post("orders/shipping/create", JSON.stringify(postData));
console.log(res);

And here I return the response: views.py

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def shipping_create_order(request):
    if request.method == 'POST':
        return JsonResponse(request.POST)

Here's what the console.log prints:

res.data // {"order:"{"order_id": 1, "customer": {"name": "Jonas Illver", "age": 18}}, "car": **car object content**}

The problem is that if I try to access those data in my django view, I always got a 500 error
I tried accessing it via:

order = request.POST['order']
# and also
data = json.loads(request.POST)
order = data['order']
# also
order = request.POST.get('order')

None os the above approaches worked, the only one that doesn't occurs an 500 error is the last one, using the POST.get, but as soon as I add the if not order: return HttpResponse("No order") line, it always return "No order"

How can I access specific info from the request.POST? Am I doing something wrong with the axios request?

1 Answers

Try using request.data to get the data passed in the body. Have a look at the rest-framework docs. Or another way to get the data is using json.loads(request.body). But using request.data is a bit shorter as it does the json.loads job for you.

Related