Rest API create class based view using a mixin

33 Views Asked by At

I have a view inheriting from APIView and another custom mixin.

None of the APIView methods is defined in the view but it is used only for declaring it as view. I need the url from only the mixin. But the mixin's url is never found django.urls.exceptions.NoReverseMatch. I am not sure how exactly to explain the problem therefore, I will provide the code:

class TypeAPI(TwoFieldListMixin, APIView):
    queryset = Type.objects.all()
    permission_classes = [IsAuthenticated]

class TwoFieldListMixin:
    query_field: str = "id"
    name_field: str = "name"

    @action(detail=False, methods=["GET"], url_name="id_code_list")
    def id_code_list(self, request: Request, *args: None, **kwargs: Any) -> Response:
        self.query_field = (
            request.query_params.get("query_field", None) or self.query_field
        )
        self.name_field = (
            request.query_params.get("name_field", None) or self.name_field
        )
        queryset: QuerySet[Any] = self.filter_queryset(self.get_queryset()).values(
            self.query_field, self.name_field
        )
        serializer: ICListSerializer = ICListSerializer(queryset, many=True)
        return Response(serializer.data)

url.py

urlpatterns = [
    path("types/", TypeAPI.as_view(), name="types"),
] + router.urls

Test that I am writing:

def test_pt_detail_api(self)->None:
    res = self.client.get(f"/api/v1/na/types/id_code_list/")
    res = self.client.get(url)
    assert res.status_code == 200

Here is the error:

/usr/local/lib/python3.10/site-packages/django/urls/resolvers.py:802: NoReverseMatch

django.urls.exceptions.NoReverseMatch: Reverse for 'types-id_code_lis...

Or applying some variations give an error:

'request_path': '/api/v1/na/types/id_code_list/', 'exception': 'Resolver404'}

Question is how can I achieve creating a simple view which inherits from a mixin and does nothing else.

0

There are 0 best solutions below