python-3.xdjangodjango-request

How to send POST request after form submit 302 in Django?


I have an implementation as follows:

  1. There is a payment form wherein user fills all the details.(API1), here I'm getting an error 302:

    enter image description here

  2. On submit of that form one of the function in my views is called.

  3. In the backend implementation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2)

    enter image description here

But the problem is coming as the request is going as GET and hence it is dropping all the form data I'm sending along with the request.

Following is the code.

views.py -->

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
    'CustomerID': 'abc',
    'TxnAmount': '1.00',
    'BankID': '1',
    'AdditionalInfo1': '999999999',
    'AdditionalInfo2': 'test@test.test',
}


payload_encoded = urlencode(payload, quote_via=quote_plus)

response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)

content = response.url
return_config = {
    "type": "content",
    "content": redirect(content)
}
return return_config

How do I send the 2nd request(API2) as POST request along with all parameters? What am I doing wrong here?

Thank you for your suggestions.


Solution

  • If the requests returns a 302 status, the new url is available in response.headers['Location']. You can keep following the new url, till you end up with a valid response.

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    payload = {
        'CustomerID': 'abc',
        'TxnAmount': '1.00',
        'BankID': '1',
        'AdditionalInfo1': '999999999',
        'AdditionalInfo2': 'test@test.test',
    }
    
    
    payload_encoded = urlencode(payload, quote_via=quote_plus)
    
    response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
    
    while response.status_code == 302:
        response = requests.post(response.headers['Location'], data=payload_encoded, headers=headers)
    
    content = response.text
    return_config = {
        "type": "content",
        "content": content
    }
    return return_config