Reset or forgot password in django rest framework

makeDEVeasy
makeDEVeasy
Published in
2 min readDec 6, 2020

When i was read so many articles and blogs in online, most of them are suggested that, if we want to reset our password we have to enter our old password, if not we can’t do it, then i was affraid that suppose we don’t know our old password in that situation, what happens……, These situations will come in general day by day basis.

So, atlast i was did it, by taking some couple of hours after researching a lot in internet, and also i was really exicted to share my code,

Here is the code:-

urls.py

from django.urls import path,includefrom . import viewsfrom rest_framework import routersrouter=routers.DefaultRouter()
urlpatterns=[path(‘register’,views.register.as_view(),name=’register’),path(‘login’,views.login.as_view(),name=’login’),path(‘logout’,views.logout.as_view(),name=’logout’),path(‘resetpassword’,views.resetpassword.as_view(),name=’resetpassword’),]

view.py

from django.shortcuts import renderfrom rest_framework import viewsetsfrom rest_framework.authtoken.models import Tokenfrom .models import *from .serializers import *from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework import statusfrom rest_framework.permissions import IsAuthenticated,AllowAny,IsAuthenticatedOrReadOnlyfrom rest_framework.decorators import action
class register(APIView):def post(self,request):serializer=registerSerializer(data=request.data)data={}if serializer.is_valid(raise_exception=True):registerdata=serializer.save()data[‘response’]=’successfully registered’data[‘username’]=registerdata.usernamedata[‘email’]=registerdata.emailreturn Response(data,status=status.HTTP_201_CREATED)else:return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)class login(APIView):def post(self,request):serializer=loginSerializer(data=request.data)if serializer.is_valid(raise_exception=True):user=serializer.save()auth.login(request,user)token,created=Token.objects.get_or_create(user=user)return Response({‘token’:token.key},status=200)return Response(‘invalid username and password try again’)
class resetpassword(APIView):def post(self,request):serializer=resetpasswordSerializer(data=request.data)alldatas={}if serializer.is_valid(raise_exception=True):mname=serializer.save()alldatas[‘data’]=’successfully registered’print(alldatas)return Response(alldatas)return Response(‘failed retry after some time’)class logout(APIView):def get(self,request):request.user.auth_token.delete()auth.logout(request)return Response(“successfully deleted”)

serializers.py

from rest_framework import serializersfrom .models import *from django.contrib.auth.models import User,authfrom rest_framework import exceptionsfrom django.contrib.auth import authenticateclass registerSerializer(serializers.ModelSerializer):username=serializers.CharField(max_length=100)email=serializers.EmailField(max_length=255,min_length=4)password=serializers.CharField(max_length=100)first_name=serializers.CharField(max_length=100)last_name=serializers.CharField(max_length=100)class Meta:model=Userfields='__all__'def save(self):email=self.validated_data['email']username=self.validated_data['username']if User.objects.filter(email=email).exists() or User.objects.filter(username=username).exists():raise serializers.ValidationError({'account':'account is already exists'})else:user=User.objects.create(username=self.validated_data['username'],first_name=self.validated_data['first_name'],last_name=self.validated_data['last_name'],email=self.validated_data['email'],)password=self.validated_data['password']user.is_active=Trueuser.set_password(password)user.save()return userclass loginSerializer(serializers.ModelSerializer):username=serializers.CharField(max_length=100)password=serializers.CharField(max_length=100)class Meta:model=Userfields='__all__'def save(self):username=self.validated_data['username']password=self.validated_data['password']if username and password:user=authenticate(username=username,password=password)if user:if user.is_active:return userelse:raise serializers.ValidationError({'user':'user is not active'})else:raise serializers.ValidationError({'user':'please enter valid user credentails'})else:raise serializers.ValidationError({'error':'username and password not to be blank'})class resetpasswordSerializer(serializers.ModelSerializer):username=serializers.CharField(max_length=100)password=serializers.CharField(max_length=100)class Meta:model=Userfields='__all__'def save(self):username=self.validated_data['username']password=self.validated_data['password']#filtering out whethere username is existing or not, if your username is existing then if condition will allow your usernameif User.objects.filter(username=username).exists():#if your username is existing get the query of your specific username user=User.objects.get(username=username)#then set the new password for your usernameuser.set_password(password)user.save()return userelse:raise serializers.ValidationError({'error':'please enter valid crendentials'})

I hope you will be understand the code, make sure please focus on highlighted part of the code, then you will be definitely understand.

--

--

makeDEVeasy
makeDEVeasy

Initiative to make the every developer easy, when they look into complex problems and make them to learn more simpler as easy……