Password Reset Email

Learn how to send a password reset link via email.

This lesson focuses on implementing the password reset email.

Create a view for requesting a password reset email

In this lesson, we’ll build a view to be called when a user requests a password reset email. Our view’s primary task is sending the user an email containing a password reset link. We can create the view class in our views.py file like this.

Press + to interact
# ... other imports
# ... updated serializers import with RequestPasswordResetEmailSerializer
from .serializers import RegistrationSerializer, EmailVerificationSerializer, ResendVerificationEmailSerializer, LoginSerializer, RequestPasswordResetEmailSerializer #Updated
# new imports
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils.encoding import smart_bytes
from django.utils.http import urlsafe_base64_encode
# .... other views
class RequestPasswordResetEmailView(generics.GenericAPIView):
serializer_class = RequestPasswordResetEmailSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
Email = request.data['email']
if User.objects.filter(email=Email).exists():
user = User.objects.get(email=Email)
uidb64 = urlsafe_base64_encode(smart_bytes(user.id))
token = PasswordResetTokenGenerator().make_token(user)
current_site = get_current_site(request=request).domain
relativeLink = reverse('password-reset-confirm', kwargs={'uidb64': uidb64, 'token': token})
absurl = 'https://' + current_site + relativeLink
email_body = "Hello! \n Use the link below to reset your password \n" + absurl
data = {'email_body': email_body,'to_email': user.email,
'email_subject':'Reset your password'}
Mail.send_email(data)
return Response({'Success': 'Password reset email sent'}, status=status.HTTP_200_OK)

In the code above, we start by declaring a serializer class in our RequestPasswordResetEmailView class in line 13, and then we create a post() method in line 16. In the post() method:

...