I am working with Django for a first time and I\'m trying to build an API and I am following some tutorials and examples and it works right, but I am running the project now
Beware of using the same names for your viewset class and your model class. This was the reason for my own error. See example of what i did
# inside member/views.py
from member.models import Member
# inheriting from model viewset but called Member
class Member(viewsets.ModelViewSet):
queryset = Member.objects.all()
...
# inside urls.py
from member.views import Member
router = routers.DefaultRouter()
router.register(r'member', Member)
Now the mistake here is its importing the member model instead of the viewset but they are of the same names
You've called it a viewset, but that doesn't make it one; you inherit from APIView which is a standalone generic view, not a viewset.
A viewset needs to inherit from viewsets.ViewSet.
In views.py, your viewset have to inherit from viewset and use it in your viewset try code below:
class SessionViewSet(viewsets.ModelViewSet):
queryset = Session.objects.all()
serializer_class = SessionSerializer
def get(self, request, format=None):
return Response("test")
For:
djangorestframework==3.11.0
Django==2.2.9
You need to change class SessionViewSet(APIView):
to:
from rest_framework import mixins, viewsets
class SessionViewSet(mixins.ListModelMixin,
viewsets.GenericViewSet):
To get it to work. The internals of DRF have changed a bit and the other solutions won't cut it any longer.
In my case, what I did was I inherited my view from viewsets.Viewset which is in rest_framework module and additionally, I added the basename = your_name argument in the router.register() function during registration.
The view would look something like:
class SessionViewSet(viewsets.ViewSet):
queryset = Session.objects.all()
serializer_class = SessionSerializer
def get(self, request, format=None):
return Response("test")
The router registeration would look something like:
router.register(r'your_app_name', YourModelNameView, basename='your_app_name')
Before Django Rest Framework v3.8 you could register an APIView
directly with a router. I did this extensively to gain a nice collated (and versioned) auto-documenting API for some very custom API endpoints. Given the choice again, I would probably write the whole thing a more standard way, but that isn't an option for everybody.
But after digging into the error, it turns out you can just patch over the problem by giving the router what it wants and adding a dummy get_extra_actions
classmethod.
class MyAPIView(APIView):
@classmethod
def get_extra_actions(cls):
return []
#...
I'm not saying this is good, but it works for now.
I've got my documentation back and I've managed to upgrade to DRFv3.8.