RevolutionTech
RevolutionTech

Reputation: 1414

Body in Request ignored when forming POST dict in Django

I am working on a Django server that takes an integer from POST data. If I send the integer via GET there's no problems, but it gets dropped when sent via POST.

I run the server with:

./manage.py runserver 0.0.0.0:8000

and then generate the POST request with:

curl -X POST -H "Content-Type: application/json" -d '{"myInt":4}' "http://0.0.0.0:8000/myURL/"

I am using PDB in the view, and here is the result I am getting for the following commands:

request.method
> 'POST'
request.body
> '{"myInt":4}'
request.POST
> <QueryDict: {}>

I have used @csrf_exempt as a decorator for the view, just to make sure that isn't causing any problems.

Currently it is baffling me that request.POST does not contain myInt, is my POST request not well-formed?

Upvotes: 2

Views: 1000

Answers (1)

Alex
Alex

Reputation: 2013

Your post request is sending JSON not application/x-www-form-urlencoded

If you look at the django docs about HttpRequest.POST .

A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.

You need to POST form encoded data. I didn't test this and haven't used curl in a while, but I believe the following should work.

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "myInt=4" "http://0.0.0.0:8000/myURL/"

Upvotes: 2

Related Questions