How to send a message to a Django 1.2 form using urllib?

Disabling this other SO question, I tried using urlencode and urlopen for POST data in the form. However, Django 1.2 gives me an error with CSRF confirmation when using. Is there a workaround?

Thank.

+5
source share
2 answers

The difference between sending data to other forms and your case is that you will first need to get the CSRF token. This can be done by first executing a GET request on the page, and then csrfmiddlewaretokenparsing it using a suitable parser.

, cookie, .

:

#!/usr/bin/python
import urllib, urllib2, cookielib
from BeautifulSoup import BeautifulSoup

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

url = urllib2.urlopen('http://localhost:8000/accounts/login/')
html = url.read()

doc = BeautifulSoup(html)
csrf_input = doc.find(attrs = dict(name = 'csrfmiddlewaretoken'))
csrf_token = csrf_input['value']

params = urllib.urlencode(dict(username = 'foo', password='top_secret', 
       csrfmiddlewaretoken = csrf_token))
url = urllib2.urlopen('http://localhost:8000/accounts/login/', params)
print url.read()
+13

csrf_exempt decorator ,

from django.views.decorators.csrf import csrf_exempt
+1

All Articles