0

I am trying to submit a form of django application using Python request module, however it gives me the following error

Error Code: 403
Message: CSRF verification failed. Request aborted.

I tried to convert the in JSON using json.dumps() and sent the request, however I am getting the same error.

I am not sure, what is missing. When I submit the form using UI, it works well. I intercepted the request using the Postman plugin as well and the request I have form is same.

import requests
session = requests.session()
session.get("http://localhost:8000/autoflex/addresult/")
csrf_token = session.cookies["csrftoken"]

print csrf_token

cookie = "csrftoken=%s" % csrf_token
headers = {"Content-Type": "Application/x-www-form-urlencoded",
           "Cookie": cookie,
           "Accept-Encoding": "gzip, deflate",
           "Connection": "keep-alive",
           "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
           "Referer": "http://localhost:8000/autoflex/addresult/"}

data = {"xml_url": xml_url, "csrfmiddlewaretoken": csrf_token}
result = session.post("http://localhost:8000/autoflex/addresult/", data=data, headers=headers)
print result.request.body
print result.request.headers
print(result.status_code, result.reason, result.content)
Gaurang
  • 171
  • 1
  • 14
  • this is a duplicate of this http://stackoverflow.com/questions/13567507/passing-csrftoken-with-python-requests – jabez Sep 14 '16 at 13:10
  • I tried putting referer URL in the header, however I am still getting the same error. I have updated the question as well. – Gaurang Sep 14 '16 at 13:22

1 Answers1

0

I was providing the other arguments in the header and I think this is creating the issue. I removed all other arguments and kept only referrer and now it's working.

import requests
session = requests.session()
session.get("http://localhost:8000/autoflex/addresult/")
csrf_token = session.cookies["csrftoken"]

data = {"xml_url": xml_url, "csrfmiddlewaretoken": csrf_token}
result = session.post("http://localhost:8000/autoflex/addresult/", data=data, headers={"Referer": "http://localhost:8000/autoflex/addresult/"})
print result.request.body
print result.request.headers
print(result.status_code, result.reason, result.content)
Gaurang
  • 171
  • 1
  • 14