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)