


What to expect from this article?
We started working on the accounts app in the previous articles, this article will build on it. It will cover
- Serializers for forgetting password, resending code, and account details.
- Views for the same APIs.
- And of course the URLs.
I'll try to cover as many details as possible without boring you, but I still expect you to be familiar with some aspects of Python and Django.
the final version of the source code can be found at https://github.com/saad4software/alive-diary-backend
Series order
Check previous articles if interested!
- AI Project from Scratch, The Idea, Alive Diary
- Prove it is feasible with Google AI Studio
- Django API Project Setup
- Django accounts management (1), registration and activation
- Django accounts management (2), login and change password
- Django Rest framework with Swagger
- Django accounts management (3) forgot password and account details (You are here ?)
How does it work?
How does forgetting password request work? the process should follow the steps
- User forgets his password, obviously ?, silly me.
- User enters his/her email address.
- An email with a verification code is sent to the email.
- User can use the email, and activation code to set a new password.
So, we need an API that takes the email address, creates an activation code, and sends it to the user, the same as the resend code API.
We also need another API that takes the email, activation code, and the new password to reset the password.
Starting with resend code API sounds like a good idea now.
Resend code API
As always, let's start with the serializer
class SendCodeSerializer(serializers.Serializer): username = serializers.CharField(required=True) def validate_username(self, value): if not is_valid_email(value): raise serializers.ValidationError("invalid_email") verification_query = get_user_model().objects.filter(username=value).exists() if not verification_query: raise serializers.ValidationError("invalid_username") return value
app_account/serializers.py
This is a generic serializer, with one field, the username, we are checking to make sure it is a valid email address, and the user is registered in the system.
now for the views
class AccountSendCodeView(APIView): permission_classes = () renderer_classes = [CustomRenderer, BrowsableAPIRenderer] @swagger_auto_schema(request_body=SendCodeSerializer) def post(self, request, *args, **kwargs): serializer = SendCodeSerializer(data=request.data) if not serializer.is_valid(): raise APIException(serializer.errors) user = get_user_model().objects.filter(username=serializer.validated_data.get("username")).first() code = VerificationCode(user=user, email=user.username) code.save() send_mail( 'Password Reset Code', 'Your password reset code is ' + str(code.code), f'AliveDiary', [user.username], fail_silently=False, ) return Response("success")
app_account/views.py
The view starts by validating the request, then fetching the user and creating a code instant for it. and finally sends the code via email to the user.
And finally, the URLs
urlpatterns = [ path('register/', AccountRegisterView.as_view()), path('activate/', AccountActivateView.as_view()), path('login/', AccountLoginView.as_view()), path('refresh/', AccountRefreshTokenView.as_view()), path('code/', AccountSendCodeView.as_view()), #new path('password/', AccountChangePasswordView.as_view()), ]
app_account/urls.py
we can test it on swagger now
Reset password API
The serializer should contain the username, the sent code, and the new password; it should check to make sure it is a valid username and code, somewhat like
class ForgotPasswordSerializer(serializers.Serializer): username = serializers.CharField(required=True) code = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate(self, data): verification_query = VerificationCode.objects.filter( user__username=data['username'], ).order_by('-id') if not verification_query.exists(): raise serializers.ValidationError("no_code") code = verification_query[0] if str(code.code) != str(data['code']): raise serializers.ValidationError("invalid_code") return data
app_account/serializers.py
all fields are required, we used the validate function in order to validate both username and code together. if there are no code instants for this user, we raise a validation error, and if the sent code doesn't match the instant code value, we inform the user by raising "invalid_code" validation error.
for the view, we need to validate the serializer at first
class SendCodeSerializer(serializers.Serializer): username = serializers.CharField(required=True) def validate_username(self, value): if not is_valid_email(value): raise serializers.ValidationError("invalid_email") verification_query = get_user_model().objects.filter(username=value).exists() if not verification_query: raise serializers.ValidationError("invalid_username") return value
app_account/views.py
if the serializer is not valid, we raise an API exception with the serializer errors, if valid, we are querying the verification instant using the serializer data. Notice that this query always exists, and the sent code is the same as the verification instant code value since this query already passed the serializer check.
Then we delete the verification instance from the database and update the user password with the "new_password" value from the serializer
finally, let's update the URLs file
class AccountSendCodeView(APIView): permission_classes = () renderer_classes = [CustomRenderer, BrowsableAPIRenderer] @swagger_auto_schema(request_body=SendCodeSerializer) def post(self, request, *args, **kwargs): serializer = SendCodeSerializer(data=request.data) if not serializer.is_valid(): raise APIException(serializer.errors) user = get_user_model().objects.filter(username=serializer.validated_data.get("username")).first() code = VerificationCode(user=user, email=user.username) code.save() send_mail( 'Password Reset Code', 'Your password reset code is ' + str(code.code), f'AliveDiary', [user.username], fail_silently=False, ) return Response("success")
app_account/urls.py
The account details API
Let's start by creating a serializer for the user model, it would look like this
urlpatterns = [ path('register/', AccountRegisterView.as_view()), path('activate/', AccountActivateView.as_view()), path('login/', AccountLoginView.as_view()), path('refresh/', AccountRefreshTokenView.as_view()), path('code/', AccountSendCodeView.as_view()), #new path('password/', AccountChangePasswordView.as_view()), ]
app_account/serializers.py
it is a model serializer, we selected the user model and listed the fields to serialize.
moving to the view, we need a view that allows users to get user details with a GET request and update user details with a POST request, it would look somewhat like
class ForgotPasswordSerializer(serializers.Serializer): username = serializers.CharField(required=True) code = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate(self, data): verification_query = VerificationCode.objects.filter( user__username=data['username'], ).order_by('-id') if not verification_query.exists(): raise serializers.ValidationError("no_code") code = verification_query[0] if str(code.code) != str(data['code']): raise serializers.ValidationError("invalid_code") return data
app_account/views.py
and the urls
class AccountForgotPasswordView(APIView): permission_classes = () renderer_classes = [CustomRenderer, BrowsableAPIRenderer] @swagger_auto_schema(request_body=ForgotPasswordSerializer) def post(self, request, *args, **kwargs): serializer = ForgotPasswordSerializer(data=request.data) if not serializer.is_valid(): raise APIException(serializer.errors) verification_query = VerificationCode.objects.filter( user__username=serializer.validated_data.get('username'), code=serializer.validated_data.get('code') ).order_by('-id') verification_query.delete() user = get_user_model().objects.filter( username=serializer.validated_data.get('username'), ).first() user.set_password(serializer.validated_data.get('new_password')) user.save() return Response("success")
app_account/urls.py
that is it! let's test this with Swagger, opening http://localhost:8555/swagger/ and using the login allows us to get a valid token. In order to test any authorized requests, we have to click on the lock ? icon, any lock icon in swagger, and provide the token with "Bearer" prefix, somewhat like "Bearer eyJhbGc..."
now testing the details API should return the account details as shown
That is it! congrats, you have a fully functional account management app that can be used in any Django app with minimal modifications
Do you believe it requires other functionalities? please make a suggestion!
We will move back to the main app in our next article, so
Stay tuned ?
The above is the detailed content of Django accounts management app ( forgot password and account details. For more information, please follow other related articles on the PHP Chinese website!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)