test.Client problems logging in (now fixed)

If you’re creating a test user for a unit test, do it this way:


newuser=User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

rather than this:


newuser=User(username="john",email="lennon@thebeatles.com",password="johnpassword")

The latter looks correct, but you’ll get problems logging in since Django stores the *hash* of the password in the db, not the clear text.

Another gotcha is that the client.login() function only works with pages where you can’t get at them until you have logged in – if the page is available to AnonymousUser, then login() will always fail.

3 Responses to “test.Client problems logging in (now fixed)”

  1. israel says:

    Hi,

    i recently ran into this problem, i had created a new user and had sent them an email to verify and authorize their account, but i wanted them to login automatically once the account is verified. Of course i couldn’t use Login() on the user object returned by the authorization because i needed to call authenticate() but to do so i needed username & password, which i could get from the user object, but password never works because it is a hash.

    are you saying that if i had used create_user(), calling user.password would return the actual password not the string?

  2. Rachel says:

    No, that’s not what I’m saying, sorry it was unclear.

    AFAICS, the password is not stored in the clear at all, so you cannot get at the cleartext password. You can only verify a given password against the stored hash to say “yes, that’s the same.”

  3. Israel says:

    yeah silly me,

    so basically a manual login without the user entering their password is impossible.

    thanks for the clarification

Leave a Reply