Manually generate Django password reset token

Ever needed to manually generate a password reset token?

For example, imagine this situation:
You create a user from a custom form, and you want the user to set his own password.
Solution: generate a password reset token,  email him the link, and let him choose his own password.

Here's how you implement this:
from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes

from django.db.models.signals import post_save

post_save.connect(user_saved, User)

def user_saved(sender, instance, created, *args, **kwargs):
if created:
context = {
'token': default_token_generator.make_token(instance),
'uid': urlsafe_base64_encode(force_bytes(,
'user': instance,
# here, send an email with this context

To display the link in the email, you must set the password reset url, and display it:
{% url 'password_reset_confirm' uidb64=uid token=token %}

urlpatterns += patterns(
url(r'^password-change/done/$', 'password_change_done', name='password_change_done'),



Popular posts from this blog

PIP - upgrade all packages from requirements.txt (interactively)

Improve font rendering for IntelliJ IDEA / Pycharm in Ubuntu