Password Reset Email
Learn how to send a password reset link via email.
We'll cover the following...
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 RequestPasswordResetEmailSerializerfrom .serializers import RegistrationSerializer, EmailVerificationSerializer, ResendVerificationEmailSerializer, LoginSerializer, RequestPasswordResetEmailSerializer #Updated# new importsfrom django.contrib.auth.tokens import PasswordResetTokenGeneratorfrom django.utils.encoding import smart_bytesfrom django.utils.http import urlsafe_base64_encode# .... other viewsclass RequestPasswordResetEmailView(generics.GenericAPIView):serializer_class = RequestPasswordResetEmailSerializerdef 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).domainrelativeLink = reverse('password-reset-confirm', kwargs={'uidb64': uidb64, 'token': token})absurl = 'https://' + current_site + relativeLinkemail_body = "Hello! \n Use the link below to reset your password \n" + absurldata = {'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: