Question

I tried the following code to log into my django admin page

#!/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_admin = 'http://localhost:8000/admin/'
url = urllib2.urlopen(url_admin)
html = url.read()
doc = BeautifulSoup(html)

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

params = urllib.urlencode(dict(username='my_admin_user',
                               password='my_password',
                               csrfmiddlewaretoken=csrf_token))

url = urllib2.urlopen(url_admin, params)
print url.read()

but I got he following error (in the printed html)

<p class="errornote">
    Please log in again, because your session has expired.
</p>

What am I doing wrong? My aim is to keep a logged in session and perform some tasks afterwards. THe fact that the user should here be an admin is not a requirement for me. It's just I don't have yet a regular login page for non admin user.

Was it helpful?

Solution

I had a similar problem where the server sent me a new session cookie on every request, and I couldn't solve it with CookieJar.

I ended up using Selenium PhantomJS webdriver. Try it in case you don't get any working solution, which was my experience.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top