Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a POST request using django?

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

Just like urllib2 sends a get request.

like image 859
zjm1126 Avatar asked Mar 15 '11 06:03

zjm1126


People also ask

How do you receive data from a Django form with a POST request?

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.

How Django process a request?

Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.


2 Answers

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.

like image 142
Rick Mohr Avatar answered Sep 24 '22 06:09

Rick Mohr


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.

like image 30
gladysbixly Avatar answered Sep 21 '22 06:09

gladysbixly