Ryan
Ryan

Reputation: 609

Python requests Post request data with Django

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!!

Upvotes: 8

Views: 28982

Answers (3)

Ursidours
Ursidours

Reputation: 103

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)

Upvotes: 2

madzohan
madzohan

Reputation: 11808

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

Upvotes: 1

Nick Rempel
Nick Rempel

Reputation: 3022

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)

Upvotes: 11

Related Questions