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!!
Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.
request. POST. get('sth') will return None if 'sth' is not in request. POST . Additionally, .get allows you to provide an additional parameter of a default value which is returned if the key is not in the dictionary.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With