chriscauley
chriscauley

Reputation: 21001

Why is my django password change not sticking?

I have a profile model I use to supplement the built in User model. I've made a function to reset the password of a user as follows:

def _reset_password(self):
    import random, string
    password = ''.join(random.choice(string.letters+string.digits) for i in range(10))
    u = self.user
    u.set_password(password)
    u.save()
    print u.check_password(password)
    return password

The heart of my problem can be summed up in three lines.

>>> p = Profile.objects.all()[0]
>>> u = User.objects.get(profile = p)
>>> u.check_password(p._reset_password())
True
False
>>>

It prints True because the check_password attempt in _reset_password is successful. It then prints False because the reset password somehow didn't stick. And now again a bit more slowly for emphasis.

>>> password = p._reset_password()
True
>>> password
'uvb9SdPOwr'
>>> u.check_password(password)
False
>>> u.set_password(password)
>>> u.save()
>>> u.check_password(password)
True
>>>

Any thoughts? I've seriously run out of ideas. I know there must be something wrong but I can't see it for the life of me. I know computers are deterministic and all, but this very clearly looks to me like the lines of code producing different effects.

Solution:

As miku said, my user was stale. But that error was in my command line test, not the actual model code. The location of the real (and exact same) problem was in the view:

p = u.profile
p._reset_password() #fail
u.blah = 'foo'
u.save() # u has old password, saving undoes line 2
p._reset_password() # this one takes because the stale u is never saved again

Upvotes: 0

Views: 1227

Answers (1)

miku
miku

Reputation: 188024

I haven't tested this, but it seems that your user object u is stale, because you retrieved it before you actually change the password. Try to

u = User.objects.get(profile = p)

after you reset the password and it should work.

Upvotes: 2

Related Questions