Kevin
Kevin

Reputation: 3431

How do I post to a Django 1.2 form using urllib?

Going off of this other SO question, I tried to use urlencode and urlopen to POST data to a form. However, Django 1.2 gives me a CSRF verification failed error when I use it. Is there a workaround?

Thanks.

Upvotes: 5

Views: 4147

Answers (2)

Manoj Govindan
Manoj Govindan

Reputation: 74795

The difference between submitting data to other forms and your case is that you will have to first get the CSRF token. This can be done by performing a GET request on the page first and then parsing the csrfmiddlewaretoken using a suitable parser.

Also keep in mind that you'll need to install a cookie jar to get this to work.

For example:

#!/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()

Upvotes: 14

Ashok
Ashok

Reputation: 10603

use the csrf_exempt decorator for the view that is handling the request

from django.views.decorators.csrf import csrf_exempt

Upvotes: 1

Related Questions