I have a flow in my django application in which I redirect the user to another service (e.g. PayPal) which after some its own processing, returns the user back on my own server. The returning point on my server is a simple HTML success page which I render using direct_to_template.
For some odd reasons, the other server sends a POST request and hence the user sees a CSRF token missing error as the other server doesn't send back any CSRF token.
How do I exempt a direct_to_template view from CSRF tokens?
You can use the csrf_exempt decorator to disable CSRF protection for a particular view.
Normally when you make a request via a form you want the form being submitted to your view to originate from your website and not come from some other domain. To ensure that this happens, you can put a csrf token in your form for your view to recognize.
Django protects against CSRF attacks by generating a CSRF token in the server, send it to the client side, and mandating the client to send the token back in the request header. The server will then verify if the token from client is the same as the one generated previously; if not it will not authorise the request.
The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.
You can use the csrf_exempt
decorator to disable CSRF protection for a particular view.
Say your url pattern is:
('^my_page/$', direct_to_template, {'template': 'my_page.html'})
Add the following import to your urls.py
:
from django.views.decorators.csrf import csrf_exempt
Then change the url pattern to:
('^my_page/$', csrf_exempt(direct_to_template), {'template': 'my_page.html'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With