How can I get a CSRF token from the command line?

Naftuli Kay picture Naftuli Kay · Nov 7, 2013 · Viewed 7.8k times · Source

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.

Answer

Paulo Scardine picture Paulo Scardine · Nov 7, 2013

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.