Issue
I'm trying to create a Patch method with Extend User Model in Django Rest Framework.
My Extend User Model:
class Profile(models.Model):
user = models.OneToOneField(User, unique=True)
bio = models.CharField
My serializers:
class UserEditSerializer(ModelSerializer):
bio = serializers.CharField(source='profile.bio')
class Meta:
model = User
fields = [
'username',
'email',
'first_name',
'last_name',
'bio'
]
My Viewsets:
class UserUpdateAPIView(ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserEditSerializer
@detail_route(methods=['PATCH'])
def edit(self, request):
user_obj = User.objects.get(user__id=request.user.id)
print(user_obj)
serializer = UserEditSerializer(user_obj, data=request.data, partial=True)
print(request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(status=status.HTTP_400_BAD_REQUEST)
Data sent with POSTMAN (json)
{ "email": "[email protected]", "profile": {"bio": "Cant send request" } }
Error:
Profile.Bio cant response true data
Photo:
Solution
UserEditSerializer's model is Profile
class. But you are try to pass as object User
instance. You need to change serializer class:
class UserEditSerializer(ModelSerializer):
bio = serializers.CharField(source='profile.bio')
class Meta:
model = User
fields = [
'username',
'email',
'first_name',
'last_name',
'bio',
]
or view:
@detail_route(methods=['PATCH'])
def edit(self, request):
user_obj = Profile.objects.get(user__id=request.user.id)
serializer = UserEditSerializer(user_obj, data=request.data, partial=True)
UPD
To make nested relation writable you need to override serializer's create
and update
methods, see details in the doc.
Example:
class UserEditSerializer(ModelSerializer):
bio = serializers.CharField(source='profile.bio')
class Meta:
model = User
fields = [
'username',
'email',
'first_name',
'last_name',
'bio',
]
def update(self, instance, validated_data):
profile = validated_data.pop('profile')
instance = super().update(instance, validated_data)
instance.profile.bio = profile.get('bio', instance.profile.bio)
instance.profile.save()
return instance
Also you need to post data like this { "email": "[email protected]", "bio": "Cant send request" }
.
Answered By - neverwalkaloner
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.