KitKit
KitKit

Reputation: 9523

Basic: How to use PATCH Method User Model in Django Rest Framework

I have problem with using PATCH Method User Model in Django Rest Framework. Hope your guy helps and save my time.

Urls.py

urlpatterns = [
  url(r'^account/edit/$', UserDetailAPIView.as_view({'patch': 'edit'}))
]

Views.py:

class UserDetailAPIView(ReadOnlyModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @detail_route(methods=['PATCH'])
        def edit(self, request):
           user_obj = User.objects.get(id=request.user.id)
           serializer = UserRegisterSerializer(user_obj, data=request.data, partial=True)
           if serializer.is_valid():
              serializer.save()
              return Response(serializer.data)
           return Response(status=status.HTTP_400_BAD_REQUEST)

Serializer:

class UserRegisterSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = [
            'email',
            'first_name',
            'last_name'
        ]

Error:

It's not partial update. It update all fields with let it blank.

Upvotes: 0

Views: 2811

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

When you use patch you need to pass only updated field to your API. For example to update email you need to send this: {'emai':'[email protected]'}. In other word you need not to provide all serializer's fied.

Upvotes: 2

Related Questions