Change Password and Update Profile — Django Rest Framework

Build a Product Review Backend with DRF — Part 9

Emre Cevik
Python | Django & Rest

--

We recently wrote an article about JWT Authentication and User Registration. We’ll add change password and update profile functionality with this article.

For change password open auth/serializers.py and type the following lines of code:

Password fields must be same. We can validate these fields with serializers validate() method. We check the user password with validate_old_password() method. Finally we save new password with update() method.

We’re ready to create the view. Open auth/views.py and create a ChangePasswordView with a update action.

Open auth/urls.py and add change password endpoint. UpdateAPIView used for update-only endpoints for a single model instance. We need to add object primary key to endpoint for update instance.

we should send a PUT request to API for checking change password endpoint. We must add password, password2 and old_password. If fields passed validations, password will be changed.

With old password we cant log in anymore

With new password as you can see in the picture below the login works very well and the access token is returning.

For update profile open auth/serializers.py and type the following lines of code:

Email and username is unique fields. When we change them, they should not be used by other users. We can validate username with validate_username() method and email with validate_email() method. Finally we save user profile with update() method.

We’re ready to create the view. Open auth/views.py and create a UpdateProfileView with a update action.

Open auth/urls.py and add update profile endpoint.

we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.

Try to change admin user. And send PUT request to auth/update_profile/1/.

As you can see in the picture below admin username changed with newuser. We have a security bug. We didnt check the user to update.

We need to add checkpoint. Logged user must be the same as the user to be updated. Open auth/serializers.py and change UserProfileSerializer’s update method.

Now we can only update our own user :

We must add this checkpoint also for change password . Open auth/serializers.py and change ChangePasswordSerializer’s update method.

You can download part 9 files from

If you want to learn more about Django, do check out the documentation, django rest framework website and make sure to check out parts of this series!

--

--