How to retrieve Django Post parameters

I'm sending data from Javascript like this:

  let payload = {
                cmd: document.getElementById('cmdInput').value
            }
            console.log('Sending payload', payload)

            fetch('/runNgen/',
                {
                    method: "POST",
                    body: JSON.stringify(payload),
                    headers: {
                        "Content-Type": "application/json"
                    }
                })

The Post operation seems to work. But on the Django side, I have

@api_view(['POST'])
def run_ngen(request):
    print("params", request.POST.keys())

and the parameters are empty. What am I doing wrong?

You can only retrieve data from HttpRequest.POST if the HttpRequest has a Content-Type header "multipart/formdata". If it doesn’t, you will get an empty QueryDict.

To get the text in the body, retrieve it from the HttpRequest.body and parse it.

import json
json.loads(request.body)#[1]

[1] This will parse text body as JSON. This will work if the text is valid JSON.

Back to Top