I'm frequently testing my application using curl
and in the past I've had to simply wrap my views with csrf_exempt
. I really don't want to do this, as I have a nasty feeling that I'll forget to do this in deployment and enjoy a lifetime of CSRF hell.
Is there a way for me to request a CSRF token using Django's shell commands? I'd like to get a token I could send with my curl
requests to test things safely.
Make an initial GET request to the form URL in order to fill the cookie jar:
$ curl http://example.com/some-form/ -o /dev/null -c cookies.txt -s
Get the value of the csrftoken
cookie:
$ grep csrftoken cookies.txt | cut -f 7
YQkfXZCKtPP0hC30NmH10jSWuf6yJA5E
When issuing a POST, just include a csrfmiddlewaretoken
field with this value (and use the same cookie jar).
I use the same trick to write end-to-end tests using the requests
library.
you can do like this
from django.middleware.csrf import _get_new_csrf_key()
request.META["CSRF_COOKIE"] = _get_new_csrf_key()
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