Reputation:
I have below setup,
view.py
class UserViewSet(viewsets.ModelViewSet):
queryset = apis_models.User.objects.all().order_by('-date_joined')
serializer_class = apis_serializers.UserSerializer
permission_classes = [HasPermPage]
http_method_names = ['get', 'patch']
Serializer.py
class UserSerializer(CustomSerializer):
group = GroupSerializer(read_only=True)
class Meta:
model = apis_models.User
fields = '__all__'
models.py
class User(DFModel, AbstractBaseUser):
GENDER_CHOICES = [
('m', 'Male'),
('f', 'Female'),
('n', 'Not sure'),
]
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255, null=True)
company = models.CharField(max_length=255, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)
date_of_birthday = models.DateField(null=True)
job_title = models.CharField(max_length=255, null=True)
description = models.TextField(null=True)
credit_card = models.CharField(max_length=255, null=True)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
group = models.ForeignKey('Group', on_delete=models.PROTECT, null=True)
Using REST API I am doing PATCH request on User model and trying to update the password. The password is getting stored as plain text. I found that set_password method store it as encrypted. Can anybody please help me to implement that. I am not sure where to include that method. In viewset or serializer? And how? Any help would be appreciated.
Upvotes: 0
Views: 214
Reputation: 88569
Override your update(...)
method (and create
method) of Serializer as,
class UserSerializer(CustomSerializer):
group = GroupSerializer(read_only=True)
class Meta:
model = apis_models.User
fields = '__all__'
def create(self, validated_data):
user = super().create(validated_data)
try:
user.set_password(validated_data['password'])
user.save()
except KeyError:
pass
return user
def update(self, instance, validated_data):
user = super().update(instance, validated_data)
try:
user.set_password(validated_data['password'])
user.save()
except KeyError:
pass
return user
Upvotes: 0