djangodjango-rest-frameworkdjango-viewsdjango-rest-viewsets

Why am I getting a TypeError when passing HTTP method dictionaries to Django REST Framework's as_view() method in ViewSets?


I created a ViewSet, in which I need to use in two URL Patterns, one is for getting the list of items and other is for getting the detail of single item. The problem is, when I pass {"get": "retrieve"} and {"get": list", "post": "create"} dictionaries in as_view() methods of my ViewSets in URL Patterns, I get the following error:

TypeError: APIView.as_view() takes 1 positional argument but 2 were given

Below is my ViewSet code:

class LungerItemViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, generics.GenericAPIView):
    permission_classes = [permissions.AllowAny,]
    def get_queryset(self):
        """Retrieves and returns all Lunger Items"""
        return LungerItem.objects.all()
    
    def get_serializer_class(self):
        """Returns serializer class"""
        return LungerItemSerializer

and below are my URL Patterns for this ViewSet:

urlpatterns = [
    path('lungar-items/', views.LungerItemViewSet.as_view({'get': 'list', 'post': 'create'}), name='lunger-item-list'),
    path('lungar-items/<int:pk>/', views.LungerItemViewSet.as_view({'get': 'retrieve'}), name='lunger-item-detail'),
]

I tried to search this issue on ChatGPT, but it did not help much. However, it helped me finding the cause of this error.

As per ChatGPT and my own research this error appears, when:

  1. We use as_view instead of as_view(). Basicaaly as_view() is a method and we should treat it like that.
  2. We pass the HTTP Methods dictionary like {"get": "list"} in an APIView class instead of a ViewSet
  3. If there are any custom Middleware used which declines the permission to use more than one HTTP Methods.

So, in my case, none of the 3 issues I highlighted above present. Because if you look at the code I shared, you can see

  1. I am using as_view()
  2. I have defined my ViewSet class instead of an APIView
  3. I am not using such custom Middleware

Kindly, help me in figuring out this issue.


Solution

  • your view is based on generics.GenericAPIView which is not a viewset. I suppose you want GenericViewSet instead