[Answer]-Sending data to an external server in django

1đź‘Ť

This makes no sense:

render_to_response('http://externalserver/pay/'...)

This method needs a relative path to an html template in your project, on your server.
https://docs.djangoproject.com/en/1.6/topics/http/shortcuts/#django.shortcuts.render_to_response

You need to think about what happens:

The action in the form tag, in the HTML, determines where the data is posted to, eg <form action="" method="post"> means “post this form to the url of the page I’m already on”… in other words the browser posts the data to the Django view which was used to render the form. This is the most common scenario.

You could post the form data directly to the external url:

<form action="http://externalserver/pay/" method="post">

Maybe this is what you want? But then your Django view wouldn’t see the data at all.

If you need to process the data in Django, then post the processed data from your server to the external url, you will need to do something different in your view. I recommend using the Requests library for a nice way to make post requests in Python.

👤Anentropic

0đź‘Ť

Your question does not make your intentions clear, unfortunately. If you mean to relay the form data between the client and a third-party server and then the server’s response back to the client, then that is referred to as proxying.

It is easily achievable using the requests library. You may find it easier to make use of
django-proxy instead of writing your own method, as it would take care of rewriting the
request headers (also known as the browser signature) in both directions.

If, on the other hand, you only wish to transfer the contents of the form to a third party
server without relaying back the server’s response, then you can simply rely on the requests library and then respond to the client using a local template.

Here is a little example:

def pay(request):
    if request.method == 'POST':
        form = PaymentForm(request.post)
    if form.is_valid():
        response = requests.post(third_party_url, data=request.post)
        'process response'
        render_to_response(success_or_failure_template)
    else:
        render_to_response(bad_data_template)
👤Ben Beirut

Leave a comment