[Answered ]-Django: byte indices must be integers or slices, not str error

1πŸ‘

βœ…

The meta data is not in the payload dictionary. At first try to extract the data key from the payload like this:

@csrf_exempt
@require_http_methods(['POST', 'GET'])
def webhook(request):
    payload = json.loads(request.body.decode("utf-8"))
    data = payload.get("data")
    if data:
        order_id = data.get("meta", {}).get("order_id")
        print(order_id)
    return HttpResponse("just testing")

Edit:

The error message
as you described above in comment JSONDecodeError: Expecting value: line 1 column 1 (char 0) indicates that json.loads() is expecting a JSON string as input.

It may be possible that request body is empty. You can check that by printing the request.body before calling json.loads().

Try this:

@csrf_exempt
@require_http_methods(['POST', 'GET'])
def webhook(request):
    payload = json.loads(request.body.decode("utf-8"))
    data = payload.get("data")
    if data and "meta" in data:
        order_id = data.get("meta").get("order_id")
        print(order_id)
    else:
        print("Meta key not found in data or data not found in payload")
        print(payload)
    return HttpResponse("just testing")

It would tell you whether the "meta" is present in data dictionary or not and also prints payload dict at the end.

0πŸ‘

request.body is byte not a dict, so you need to load the string as JSON.

payload = json.loads(request.body)

Leave a comment