James Lee
James Lee

Reputation: 926

How to encrypt password in Django from the server side

I am new to Django. I am wondering how I can encrpyt the password

I am PUT from the REST API. I want my code to do something like this

Views.py

#Users Viewset
class UsersViewSet(viewsets.ModelViewSet):
    queryset = Users.objects.all()
    m = Users(username=restapibodyusername, email=restapibodyenmail, password=make_password(pwdrestapibodypassword)
    serializer_class = UsersSerializer

Seralizer.py

# Users Seralizer
class UsersSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = '__all__'

I can encrypt it in the client side but I prefer to do it in the serverside. Is this even possible?

Upvotes: 0

Views: 181

Answers (1)

Mukul Kumar
Mukul Kumar

Reputation: 2103

# you have to import make_password

from django.contrib.auth.hashers import make_password

# If you are using PUT request, then you can write update function in your serializer

def update(self, instance, validatedData):
    # get the password and hash it
    password = validatedData.get("password", instance.password)
    hash_password = make_password(password)

    instance.username = validatedData.get("username", instance.username)
    instance.email = validatedData.get("email", instance.email)
    instance.password = hash_password

    instance.save()

    return instance

Upvotes: 1

Related Questions