Subscribe to RSS Feed

Django Site Login Script

January 8, 2012 by Tom Coote

Just having a play around with a Python script that will login to a standard Django login form. I thought I’d share it as it’s quite interesting and I’m sure someone might find a use for it.

It uses the standard Python modules urllib2, urllib and cookielib. It also requires BeautifulSoup for getting the generated CSRF token from the Django login form to use with the authentication credentials.

Here is the script.

import urllib2
import urllib
import cookielib
from BeautifulSoup import BeautifulSoup

LOGIN_URL = 'http://a-django-site.com/login/'

# for handling cookies to and from all requests we make in this script
# because the site uses cookies for authentication data.
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

# need the CSRF token from the login form that allows us to login
login_form = BeautifulSoup(opener.open(LOGIN_URL).read())
csrf = login_form.find('input', attrs={'name': 'csrfmiddlewaretoken'}).attrMap

# sign in by sending the correct credentials to the login form
credentials = {'username': 'admin',
               'password': '123456',
               'remember': '',
               'csrfmiddlewaretoken': csrf['value']
               }

req = urllib2.Request(LOGIN_URL, urllib.urlencode(credentials))
raw_html = opener.open(req).read()

# test if the login was successful
login_success = 'sessionid' in [c.name for c in cj]
print login_success and 'Login successful' or 'Login failed'

Pretty straight forward. Once logged in BeautifulSoup could be used to easily navigate and scrape data from the authenticated web site.

One Response to “ Django Site Login Script ”

  1. Dan
    January 9, 2012 at 2:09 pm

    Django’s built in Client() from the testing suite also does this, but neat trick all the same :-)

Leave a Reply