How can i update my user profile using serializer, I got this error when i update my user profile: Write an explicit .update() method for serializer accounts.serializers.AccountProfileSerializer, or set read_only=True on dotted-source serializer fields.
class AccountProfileSerializer(serializers.ModelSerializer):
gender = serializers.CharField(source='accountprofile.gender')
phone = serializers.CharField(source='accountprofile.phone')
location = serializers.CharField(source='accountprofile.location')
birth_date = serializers.CharField(source='accountprofile.birth_date')
biodata = serializers.CharField(source='accountprofile.biodata')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'last_login', 'date_joined',
'gender', 'phone', 'location', 'birth_date', 'biodata')
class AccountProfileViewSet(APIView):
permission_classes = [
permissions.IsAuthenticated,
]
def get(self, request, format=None):
profile = User.objects.get(pk=self.request.user.pk)
serializer = AccountProfileSerializer(profile, many=False)
return Response(serializer.data)
def put(self, request):
profile = User.objects.get(pk=self.request.user.pk)
serializer = AccountProfileSerializer(profile, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I solved this by override update method in serializer
class AccountProfileSerializer(serializers.ModelSerializer):
gender = serializers.CharField(source='accountprofile.gender')
phone = serializers.CharField(source='accountprofile.phone')
location = serializers.CharField(source='accountprofile.location')
birth_date = serializers.CharField(source='accountprofile.birth_date')
biodata = serializers.CharField(source='accountprofile.biodata')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'gender',
'phone', 'location', 'birth_date', 'biodata')
def update(self, instance, validated_data):
profile_data = validated_data.pop('accountprofile')
profile = instance.accountprofile
# * User Info
instance.first_name = validated_data.get(
'first_name', instance.first_name)
instance.last_name = validated_data.get(
'last_name', instance.last_name)
instance.email = validated_data.get(
'email', instance.email)
instance.save()
# * AccountProfile Info
profile.gender = profile_data.get(
'gender', profile.gender)
profile.phone = profile_data.get(
'phone', profile.phone)
profile.location = profile_data.get(
'location', profile.location)
profile.birth_date = profile_data.get(
'birth_date', profile.birth_date)
profile.biodata = profile_data.get(
'biodata', profile.biodata)
profile.save()
return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With