How can one generate password reset URLS?

I’d like to find an easy way to send users a password reset link; the same kind of link sent in the default Django password reset email.

At the moment I have the following method on my User class.

from django import utils
from django.conf import settings
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.urls import reverse

class User(...):
    def get_password_reset_url(self):
        base64_encoded_id = utils.http.urlsafe_base64_encode(utils.encoding.force_bytes(
        token = PasswordResetTokenGenerator().make_token(self)
        reset_url_args = {'uidb64': base64_encoded_id, 'token': token}
        reset_path = reverse('password_reset_confirm', kwargs=reset_url_args)
        reset_url = f'{settings.BASE_URL}{reset_path}'
        return reset_url

Is there an easier way to go about getting the password reset URL for user?

I’m not sure there would be one - at lease not one that’s going to work with the standard password reset views.

If you look through the source code for how this is done within the provided methods, you’ll see that this is pretty much what their method boils down to.

I’m curious - what is the issue you’re trying to address? (Why do you think this is too much or too complicated?)

Thank you for the response Ken.

I would like to send my users a password reset link via SMS. They provide us with an email address and a phone number. We’d like them to be able to recover an account with either.

I think the hard parts are me getting a little nervous when wiring together authorization logic, and calling Django internals I don’t usually use. So far the implementation I put in the post has worked, but I wanted to ask just to be extra safe.

This is one area where Django has an excellent third-party package one can use. I’d look at django-allauth:


1 Like