How to use curl with Django, csrf tokens and POST requests

前端 未结 6 2033
一个人的身影
一个人的身影 2020-12-07 13:10

I\'m using curl to test one of my Django forms. The calls I\'ve tried (with errors from each, and over multiple lines for readability):

(1):

curl
-d          


        
6条回答
  •  -上瘾入骨i
    2020-12-07 13:57

    A mixture of Damien's response and your example number 2 worked for me. I used a simple login page to test, I expect that your registration view is similar. Damien's response almost works, but is missing the sessionid cookie.

    I recommend a more robust approach. Rather than manually entering the cookies from other requests, try using curl's built in cookie management system to simulate a complete user interaction. That way, you reduce the chance of making an error:

    $ curl -v -c cookies.txt -b cookies.txt host.com/registrations/register/
    $ curl -v -c cookies.txt -b cookies.txt -d "email=user@site.com&a=1&csrfmiddlewaretoken=" host.com/registrations/register/
    

    The first curl simulates the user first arriving at the page with a GET request, and all the necessary cookies are saved. The second curl simulates filling in the form fields and sending them as a POST. Note that you have to include the csrfmiddlewaretoken field in the POST data, as suggested by Damien.

提交回复
热议问题