'Django check_token(user, token) fails in view but works in test/shell_plus?

Getting the strangest behavior. This fails in normal Django code (view):

user = User.objects.get(...)
uid = urlsafe_base64_encode(force_bytes(user.pk))
token = default_token_generator.make_token(user)

print("CHECK TOKEN:", default_token_generator.check_token(to, token))
# this prints True!

send_email_function(user, uid, token)
# When using password reset email, token is denied

Then when using the token to reset password, the password reset view claims the token is invalid. If I make a management command that calls the same code to send a password reset email: the token works!

This works in shell_plus, same code basically:

>>> from django.contrib.auth.tokens import default_token_generator
>>> from django.utils.encoding import force_bytes
>>> from django.utils.http import urlsafe_base64_encode
>>> user = User.objects.last()
>>> token = default_token_generator.make_token(user)
>>> default_token_generator.check_token(user, token)
True

I've printed out the SECRET_KEY in each case and that seems fine. Inspecting the make_token function has lead me to trying to set a password and last_login which have not helped.

Very confusing!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source