In this tutorial you will learn how to create Change / Update Password and Reset / Forgot Password API using Django Rest Framework. This tutorial is a second part of our Django REST Framework Tutorial – Register Login Logout API.

Django Change and Reset Password API
change reset password

Change Password API using Django Rest Framework

Django Change Password API will create a new password with the verification of old password.

In serializers.py, add the following code –

from rest_framework import serializers
from django.contrib.auth.models import User

class ChangePasswordSerializer(serializers.Serializer):
    model = User

    """
    Serializer for password change endpoint.
    """
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)

In views.py, add the following code –

from rest_framework import status
from rest_framework import generics
from rest_framework.response import Response
from django.contrib.auth.models import User
from .serializers import ChangePasswordSerializer
from rest_framework.permissions import IsAuthenticated   

class ChangePasswordView(generics.UpdateAPIView):
    """
    An endpoint for changing password.
    """
    serializer_class = ChangePasswordSerializer
    model = User
    permission_classes = (IsAuthenticated,)

    def get_object(self, queryset=None):
        obj = self.request.user
        return obj

    def update(self, request, *args, **kwargs):
        self.object = self.get_object()
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            # Check old password
            if not self.object.check_password(serializer.data.get("old_password")):
                return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST)
            # set_password also hashes the password that the user will get
            self.object.set_password(serializer.data.get("new_password"))
            self.object.save()
            response = {
                'status': 'success',
                'code': status.HTTP_200_OK,
                'message': 'Password updated successfully',
                'data': []
            }

            return Response(response)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

In urls.py file, add path –

from .views import ChangePasswordView
from django.urls import path

urlpatterns = [
    path('api/change-password/', ChangePasswordView.as_view(), name='change-password'),
]

That’s it. Now go to url ( http://localhost:8000/api/register/ ) in your browser or post and the following in content.

{
    "old_password": "[email protected]",
    "new_password": "[email protected]"
}

And in response, you will get similar data –

{
    "status": "success",
    "message": "Password updated successfully",
}

Reset Password API using Django Rest Framework

Here we will use a library called django-rest-passwordreset for creating Reset or Forgot Password API using Django Rest Framework.

First we need to install django-rest-passwordreset library using pip-

pip install django-rest-passwordreset

Add it to INSTALLED_APPS in settings.py file –

INSTALLED_APPS = [
    ...
    'rest_framework',
    'django_rest_passwordreset',
]

and then we need to migrate reset password fields to database –

python manage.py migrate

Now in urls.py file, add the path –

from django.urls import path, include

urlpatterns = [
    ...
    path('api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')),
]

Go to – http://localhost:8000/api/password_reset/

In models.py add following signal for sending email.

from django.dispatch import receiver
from django.urls import reverse
from django_rest_passwordreset.signals import reset_password_token_created
from django.core.mail import send_mail  


@receiver(reset_password_token_created)
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs):

    email_plaintext_message = "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key)

    send_mail(
        # title:
        "Password Reset for {title}".format(title="Some website title"),
        # message:
        email_plaintext_message,
        # from:
        "[email protected]",
        # to:
        [reset_password_token.user.email]
    )

For printing in Backend Terminal Console, add following line in settings.py

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Copy link which is in email, will be similar to /api/password_reset/?token=339e80fe05e5ca9fc74799213f81a093d1f

Learn How to send Email in Django – Link

Now copy that token which comes in email and and post token and password to /api/password_reset/confirm/ api url.

{
    "token":"3339e80fe05e5ca9fc74799213f81a093d1f",
    "password":"[email protected]"
}

In Response you will get –

{
    "status": "OK"
}

Find this tutorial on GitHub – https://github.com/studygyaan/django-rest-framework-tutorial