I have a Django REST framework viewset with multiple actions such as list, create, and more. When I send a GET request, I noticed that some actions are executed multiple times, and the action is sometimes set to "None." Can anyone help me understand why this is happening and how to resolve it?
Here is my view code for reference: Url :
path(
"question/questionnaire/<int:questionnaire_id>/",
QuestionModelViewSet.as_view({"get": "list", "post": "create"}),
name="question_R",
),
path(
"question/<int:pk>/",
QuestionModelViewSet.as_view(
{
"get": "retrieve",
"delete": "destroy",
"patch": "partial_update",
"put": "update",
}
),
name="question_URD",
),
permission :
class IsStaffDoctorOrIsStaffHumanResource(permissions.BasePermission):
def has_permission(self, request, view):
# Check if the user belongs to the "staff_human_resource" group
return request.user.groups.filter(name="staff_doctor").exists() or request.user.groups.filter(name="staff_human_resource").exists()
View :
class QuestionModelViewSet(viewsets.ModelViewSet):
pagination_class = LargePagination
def get_permissions(self):
if self.action == "retrieve" or self.action == "list":
permission_classes = [IsStaffDoctorOrIsStaffHumanResource]
else:
permission_classes = [DjangoModelPermissions]
return [permission() for permission in permission_classes]
def get_queryset(self):
print(self.action)
if self.action == "retrieve" or self.action == "update" or self.action == "partial_update" or self.action == "delete" or self.action == None :
pk = self.kwargs.get("pk")
data = Question.objects.filter(pk=pk)
return data
if self.action == "list" or self.action == "create":
questionnaire_id = self.kwargs.get("questionnaire_id")
data = Question.objects.filter(questionnaire=questionnaire_id)
return data
else:
pk = self.kwargs.get("pk")
data = Question.objects.filter(pk=pk)
return data
def get_serializer_class(self):
if self.action == "update" or self.action == "partial_update":
return QuestionUpdateSerializer
else:
return QuestionSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(
data=request.data,
many=False,
context={
"request": self.request,
"questionnaire_id": self.kwargs.get("questionnaire_id"),
},
)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
print Output :
list
create
create
None
list
I think that the problem is DjangoModelPermissions I would appreciate any insights or guidance on why the actions are being executed multiple times and how to ensure that the correct action is executed for a GET request.
Thank you!
When I removed the DjangoModelPermissions The None action was no longer shown