How to send a POST request using django?

Question:

I dont want to use html file, but only with django I have to make POST request.

Just like urllib2 sends a get request.

Asked By: zjm1126

||

Answers:

You can use urllib2 in django. After all, it’s still python. To send a POST with urllib2, you can send the data parameter (taken from here):

urllib2.urlopen(url[, data][, timeout])

[..] the HTTP request will be a POST instead of a GET when the data parameter is provided

Answered By: Gabi Purcaru

In Python 2, a combination of methods from urllib2 and urllib will do the trick. Here is how I post data using the two:

post_data = [('name','Gladys'),]     # a sequence of two element tuples
result = urllib2.urlopen('http://example.com', urllib.urlencode(post_data))
content = result.read()

urlopen() is a method you use for opening urls.
urlencode() converts the arguments to percent-encoded string.

Answered By: gladysbixly

The only thing you should look at now:

https://requests.readthedocs.io/en/master/

Answered By: lajarre

Here’s how you’d write the accepted answer’s example using python-requests:

post_data = {'name': 'Gladys'}
response = requests.post('http://example.com', data=post_data)
content = response.content

Much more intuitive. See the Quickstart for more simple examples.

Answered By: Rick Mohr

Pay attention, that when you’re using requests , and make POST request passing your dictionary in data parameter like this:

payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', data=payload)

you are passing parameters form-encoded.

If you want to send POST request with only JSON (most popular type in server-server integration) you need to provide a str() in data parameter. In case with JSON, you need to import json lib and make like this:

 payload = {'param1':1, 'param2':2}
 r = request.post('https://domain.tld', data=json.dumps(payload))`

documentation is here

Answered By: fanni
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.