Search code examples
djangodjango-csrf

HTTP post request in Django


I am trying to do the following:

1) A payment solution is supposed to send an HTTP Post to my site
2) I would like to read the contents of the request(xml) and update my records to reflect the payment

I am trying this for the first time. When I create a URL path, and send a post to that address I get the csrf error.

Is there a way using Django wherein I can accept a post and don't have to return a response.

Thanks Tanmay


Solution

  • Your view should return an http response, otherwise you will get an error. However, Django does not mind if that response does not contain any content. Your view can be as simple as:

    from django.http import HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def my_view(request):
        # do something with request.POST
        return HttpResponse("")
    

    Since it is a third party that is submitting the post request, and not a user submitting a form on your site, you can mark the view as exempt from CSRF protection using the csrf_exempt decorator, as above.

    Note that anyone could submit a post request to your url, so you should have some way of checking that the response is genuine. Your payment solution should be able to advise a suitable way to do this.