How to create restore password function with Django rest framework?

I have a Django Rest Framework app. And I try to create reset password function. But the problem I am facing is that some functions are not called by the Django Rest Framework.

So I have a module accounts–> templates –> registration and then the html templates in it. Like:

  • password_reset
  • password_reset_confirm
  • password_reseet_done
  • password_reset_form

And in the accounts module I have a views.py file:

from django.shortcuts import render
from django.utils.http import urlsafe_base64_decode
from django.utils.encoding import force_str
from django.contrib.auth.tokens import default_token_generator
from rest_framework import generics
from .serializers import ChangePasswordSerializer

class PasswordResetConfirmView(generics.GenericAPIView):
    serializer_class = ChangePasswordSerializer

    def get(self, request, uidb64, token, *args, **kwargs):
        try:
            uid = force_str(urlsafe_base64_decode(uidb64))
            user = UserModel.objects.get(pk=uid)
        except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
            user = None

        if user is not None and default_token_generator.check_token(user, token):
            return render(request, 'registration/password_reset_confirm.html', {'validlink': True, 'user': user, 'uidb64': uidb64, 'token': token})
        else:
            return render(request, 'registration/password_reset_confirm.html', {'validlink': False})

    def post(self, request, uidb64, token, *args, **kwargs):
        try:
            uid = force_str(urlsafe_base64_decode(uidb64))
            user = UserModel.objects.get(pk=uid)
        except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
            user = None

        if user is not None and default_token_generator.check_token(user, token):
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response({"message": "Password has been reset successfully."}, status=status.HTTP_200_OK)
        else:
            return Response({"error": "Invalid link."}, status=status.HTTP_400_BAD_REQUEST)

And a serializers.py file:

from django.utils.translation import gettext as _
from django.contrib.auth import (get_user_model, authenticate)
from rest_framework import serializers

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.contrib.auth import get_user_model
from django.template.loader import render_to_string
from rest_framework import serializers
from django.core.mail import send_mail
from django.urls import reverse
from django.conf import settings

from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth.models import User
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_decode
from rest_framework import serializers




UserModel = get_user_model()

class PasswordResetSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def validate_email(self, value):
        if not UserModel.objects.filter(email=value).exists():
            raise serializers.ValidationError("There is no user with this email address.")
        return value

    def save(self):
        email = self.validated_data['email']
        user = UserModel.objects.get(email=email)

        # Generate token and uid
        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        # Prepare email
        reset_link = self.context['request'].build_absolute_uri(
            reverse('accounts:password_reset_confirm', kwargs={'uidb64': uid, 'token': token})
        )
        subject = "Password Reset Requested"
        email_template_name = "registration/password_reset_email.html"
        context = {
            "email": user.email,
            "reset_link": reset_link,
            "user": user,
        }
        email = render_to_string(email_template_name, context)
        
        # Send email
        send_mail(subject, email, settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=False)

class PasswordResetConfirmSerializer(serializers.Serializer):
    uidb64 = serializers.CharField()
    token = serializers.CharField()
    new_password = serializers.CharField(write_only=True)
    re_new_password = serializers.CharField(write_only=True)

    def validate(self, data):
        uid = force_str(urlsafe_base64_decode(data.get('uidb64')))
        self.user = User.objects.get(pk=uid)
        if not default_token_generator.check_token(self.user, data.get('token')):
            raise serializers.ValidationError("The reset link is invalid or has expired")
        if data.get('new_password') != data.get('re_new_password'):
            raise serializers.ValidationError("The two password fields didn't match.")
        return data

    def save(self):
        self.user.set_password(self.validated_data['new_password'])
        self.user.save()

And my general urls.py file looks:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from drf_spectacular.views import (SpectacularAPIView, SpectacularSwaggerView)

from rest_framework.schemas import get_schema_view

urlpatterns = [
   
    path('admin/', admin.site.urls),
    path('api/', include('DierenWelzijnAdmin.urls')),
    path('api-auth/', include('rest_framework.urls')),
    path('schema/', get_schema_view()),
    path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
    path('api/docs', SpectacularSwaggerView.as_view(url_name='api-schema'),
         name='api-docs'),
    path('accounts/', include('accounts.urls', namespace='accounts')),  

And the urls.py in the accounts module looks:

from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token
from accounts import views
from .views import( ChangePasswordView,  PasswordResetView,
    PasswordResetConfirmView, send_test_email )

app_name='accounts'

urlpatterns = [
    
    path('password-reset/', PasswordResetView.as_view(), name='password-reset'),      
    path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('send-test-email/', send_test_email, name='send_test_email'),

And I try to call the api call password-reset with the url:

http://127.0.0.1:8000/accounts/password-reset/

But then every time I get this error:

NoReverseMatch at /accounts/password-reset/ Reverse for
‘password_reset_confirm’ not found. ‘password_reset_confirm’ is not a
valid view function or pattern name. Request Method: POST Request
URL: http://127.0.0.1:8000/accounts/password-reset/ Django
Version: 5.0.6 Exception Type: NoReverseMatch Exception Value:
Reverse for ‘password_reset_confirm’ not found.
‘password_reset_confirm’ is not a valid view function or pattern name.

Question: how to call the api call: password-reset without error?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật