How to Hash Django user password in Django Rest Framework?
You could also use a field validation function for the password
field by adding a validate_password
method to your serializer and make it return the hash.
from rest_framework.serializers import ModelSerializer
from django.contrib.auth.hashers import make_password
class UserSerializer(ModelSerializer):
class Meta:
model = backend.models.User
fields = ('username', 'email', 'password',)
validate_password = make_password
You can overwrite the perform_create method in CreateAPIView
from rest_framework.generics import CreateAPIView
class SignUpView(CreateAPIView):
serializer_class = SignUpSerializers
def perform_create(self, serializer):
instance = serializer.save()
instance.set_password(instance.password)
instance.save()
You can try it in this way
from django.contrib.auth.hashers import make_password
user = User.objects.create(
email=validated_data['email'],
username=validated_data['username'],
password = make_password(validated_data['password'])
)