R. Anderson
R. Anderson

Reputation: 39

Django REST Framework - method patch not allowed with UpdateModelMixin

I would like to update a record in my database with the REST framework. I'm getting an message of method not allowed for anything but "GET".

views.py

class MetadataViewTest(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):

    queryset = deployment.objects.all()
    serializer_class = SerializerTest

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

urls.py

urlpatterns = [ 
    path('api/metadata_test/<int:pk>/', views.MetadataViewTest.as_view())
]

serializers.py

class SerializerTest(serializers.ModelSerializer):
    class Meta:
        model = deployment
        fields = [field.name for field in deployment._meta.fields]

I've tried the request through postman as a PATCH PUT or POST at api/metadata_test/20/

This is a simplified version, I plan on overriding the get put and delete functions.

Upvotes: 0

Views: 4728

Answers (2)

Shubham Aggarwal
Shubham Aggarwal

Reputation: 11

All you need to do is instead of calling /api/metadata_test/ call /api/metadata_test/12345/

Where 12345 is the id/pk of the record. I am assuming that id is the primary key of the model.

Upvotes: 1

Huy Chau
Huy Chau

Reputation: 2240

Update your code to:

views.py

class MetadataViewTest(generics.RetrieveUpdateDestroyAPIView):

    queryset = deployment.objects.all()
    serializer_class = SerializerTest

urls.py

urls.py

urlpatterns = [ 
    path('api/metadata_test/', views.MetadataViewTest.as_view()) # Should to the list, not detail
]

Call API like this PUT/PATCH: api/metadata_test/20/


It better if you use viewsets.GenericViewSet instead of generics.GenericAPIView because you are using ...ModelMixin.

Your router like this

from rest_framework import routers


api_router = routers.DefaultRouter()

api_router.register('metadata_test', MetadataViewTest, basename='metadata_test')
...

Upvotes: 1

Related Questions