How to update a user password with Django RestFramework

parksontano

Daniel Parkson Tano

Posted on March 31, 2023

How to update a user password with Django RestFramework

You have probably been in situation where you coded a web app using a frontend framework like React Js or Angular and django for backend and django restframework to create API.
You need to allow a user (Admin or management) to update another users password directly from the frontend.
For example, let's assume you built a Human Resource management app for a company and the user with administrative priviledges can create an employee as well as update their credentials (password and username or email).

To do this after creating your user model in models.py file, now you will have to create Change password serializer in the serializers.py file

class ChangePasswordSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=True, validators=[validate_password])

    class Meta:
        model = User
        fields = ('password',)


    def update(self, instance, validated_data):

        instance.set_password(validated_data['password'])
        instance.save()

        return instance
Enter fullscreen mode Exit fullscreen mode

The above block of code is a serializer that recieves the new password and updates the user account.
But no user credentials was passed for instance email or username. The next thing you have you do now is to create a view (ChangePasswordView) in your views.py files.

from rest_framework import generics 
class ChangePasswordView(generics.UpdateAPIView):

    queryset = User.objects.all()
    serializer_class = ChangePasswordSerializer
Enter fullscreen mode Exit fullscreen mode

You are using a class base generic view so that the methods of the updateAPIView (Put and Patch) which will be inherited by your view class.

After creating your view class the last thing to do is to create url path to your view class in the urls.py file. As such

path('change_password/<int:pk>', ChangePasswordView.as_view(), name='auth_change_password')

The path takes a single argument which is the user_Id (or the primary key of your user model)

You can now make put request from your frontend code to the change_password/<int:pk> url.
Below is a code you can use with axios to make the http request

    const update_password = async (event) => {
        event.preventDefault();
        new_password != "" &&
            (await axios
                .put(API_URL + `account/change_password/${employee.user.id}`, {
                    password: new_password
                })
                .then(async (response) => {
                    alert("Password Successfully Changed")
                })
                .catch(async (err) => {
                    console.log(err);
                }))
Enter fullscreen mode Exit fullscreen mode

Looking at the above code, let's take a walk through each statement:

new_password != "" &&
checks is the new password field is not null (empty). if the new password field is not null then the next part of the code is executed

await axios.put(API_URL + `account/change_password/${employee.user.id}`, {password: new_password })
Enter fullscreen mode Exit fullscreen mode

We are using Async/await inoder to asynchronously execute the code. You have to pass in your change passowrd url path (API_URL + `account/change_password/) and the userID of the account you want to update thr password (for instance the userID here is stored in employee.user.id). You then make a put request using axios or Javascript Fetch.

This function will have to be called when a specific button is click (add OnClick={update_password} to your button).

💖 💪 🙅 🚩
parksontano
Daniel Parkson Tano

Posted on March 31, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related