8

I'm trying to send a simple post request to a very simple django server and can't wrap my head around why the post data isn't appearing in the requests post dictionary and instead its in the request body.

Client code:

    payload = {'test':'test'}
    headers = {'Content-type': 'application/json','Accept': 'text/plain'}
    url = "localhost:8000"
    print json.dumps(payload)
    r = requests.post(url,data=json.dumps(payload),headers=headers)

Server Code:

def submit_test(request):
    if request.method == 'POST':
          print 'Post: "%s"' % request.POST
          print 'Body: "%s"' % request.body
          return HttpResponse('')

What is printed out on the server is:

Post: "<QueryDict: {}>"
Body: "{"test": "test"}"

I've played around with the headers and sending the data as a straight dictionary and nothing seems to work.

Any ideas? Thanks!!

0

3 Answers 3

11

The POST dictionary only contains the form-encoded data that was sent in the body of the request. The body attribute contains the raw body of the request as a string. Since you are sending json-encoded data it only shows up in the raw body attribute and not in POST.

Check out more info in the docs.

Try form-encoded data and you should see the values in the POST dict as well:

payload = {'test':'test'}
url = "localhost:8000"
requests.post(url, data=payload)
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that and it was giving me the same thing. Is there anything grossly wrong with just reading it out of the body and processing it from there? Thanks!
If you are communicating with the server via json, reading the content out of the body attribute is the canonical method I believe. It's what I've done in the past. :)
2

Specifying a user-agent in the headers should enable Django to interpret the raw data of the body and to correctly populate the POST dictionary. The following should work:

payload = {'test': 'test'}
url = "http://localhost:8000"
headers = {'User-Agent': 'Mozilla/5.0'}
requests.post(url, data=payload, headers=headers)

1 Comment

I know, this comment is late, but this should be the correct solution because that's the only working method!
1

You should remove 'Content-type' from headers and use default one which is 'multipart/form-data'

response = client.post(
    '/some_url/',
    data={'post_key': 'some_value'},
    # content_type='application/json'
)

If you uncomment 'content_type' data will be only in request.body

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.