Django submit form using Request Module, CSRF Verification failed
<p>I am trying to submit a form of django application using Python request module, however it gives me the following error</p>

<blockquote>
  <p>Error Code: 403<br>
  Message: CSRF verification failed. Request aborted.</p>
</blockquote>

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

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

<pre><code>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)
</code></pre>

<p>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. </p>

<pre><code>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)
</code></pre>

python django python-2.7 django-forms request