Reputation: 61
I'm using UserProfileSerializer
to validate fields in patch
request:
password = request.data.get('password', '')
if password:
if len(password) < 6:
return Response(status=status.HTTP_400_BAD_REQUEST)
hashed_pass = make_password(password)
serializer = UserProfileSerializer(instance=user,
data={'last_name': request.data.get('last_name', ''),
'password': hashed_pass,
partial=True)
else:
serializer = UserProfileSerializer(instance=user, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
and this is my serializer:
class UserProfile(models.Model):
class meta:
abstract = True
password = models.CharField(_('password'), max_length=128, blank=True)
last_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=True)
class UserProfileSerializer(ModelSerializer):
class Meta:
model = UserProfile
When i'm updating password, the last_name
made empty!!
How i prevent it?
Upvotes: 1
Views: 43
Reputation: 53774
This bit of code (which is syntactically invalid (I assume you copy pasted incorrectly)) is to blame
data={'last_name': request.data.get('last_name', ''),
'password': hashed_pass,
partial=True)
If the last name is not in the post data you are setting the last name to blank. You were probably looking for something like:
data={'last_name': request.data.get('last_name', user.last_name),
'password': hashed_pass}
which results in the current last name being preserved.
Upvotes: 1