0

I use Pinax, and I am trying to perform login test on account project, using requests module.

I did this

def test001_login(self):
    #cookies = {'csrftoken': 'a8356fd05b25fad7004994fd5da89596'}
    r = requests.post(self.loginurl, data={'username':self.username, 'password': self.password}, auth=(self.username, self.password),allow_redirects=True)

    print r.status_code
    print r.text
    print r.cookies

Cookie returned is empty!! With get method, I get a cookie. What is causing this issue?

r.text result:

    <p>Reason given for failure:</p>
    <pre>
    No CSRF or session cookie.
    </pre>

  <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
  <a
  href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's
  CSRF mechanism</a> has not been used correctly.  For POST forms, you need to
  ensure:</p>

I tried to stick in cookies but it still gave me 403 error.

Piotr Dobrogost
  • 41,292
  • 40
  • 236
  • 366
CppLearner
  • 16,273
  • 32
  • 108
  • 163

2 Answers2

2

Your post is not handing the CSRF Token to the login. Does this work:

r = requests.post(self.loginurl, data={'csrf_token': django.middleware.csrf.get_token(), 'username':self.username, 'password': self.password}, auth=(self.username, self.password),allow_redirects=True)
Furbeenator
  • 8,106
  • 4
  • 46
  • 54
  • Thank you. I was going to do that too. Am I supposed to import like this? `from django.middleware import csrf` – CppLearner Mar 13 '12 at 22:22
0

CSRF works by adding a hidden field containing a varying token into the form then testing for it when the form is posted. You're getting this error because you haven't included the token in the post. You can work around it, or turn it off, or use the "proper" unit testing stuff.

See the CSRF documentation.

Might be worthwhile looking up Client if you're doing test driven development

John Mee
  • 50,179
  • 34
  • 152
  • 186