Kuracha
Kuracha

Reputation: 321

Two post methods in one class based view

Is there possibility to have 2 post methods in one class based view?

I tried to do something like this but of course it doesn't work

My custom view:

class UserExamDetail(APIView):

    def get_queryset(self, pk):
        return Exam.objects.get(pk=pk)

    def get(self, request, pk):
        exam = self.get_queryset(pk=pk)
        if exam:
            exam_closed = 0
            exam_opened = 0
            c_questions = ClosedQuestion.objects.filter(exam=exam)
            o_questions = OpenedQuestion.objects.filter(exam=exam)
            for question in c_questions:
                points = int(question.points)
                exam_closed += points
            for question in o_questions:
                points = int(question.points)
                exam_opened += points
            exam.score = exam_closed + exam_opened
            exam.save()
        serializer = ExamCreatorSerializer(exam)
        return Response(serializer.data)

    def post(self, request, pk):
        serializer = ClosedQuestionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(exam=pk)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

    def post(self, request, pk):
        serializer = OpenedQuestionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(exam=pk)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

Only first post works and when i try to change function name on for example: post1 and post 2 then Django won't recognize this method as post. If there is possibility to do this, then I'm also curious if I should do this kind of view or maybe Post methods should be separate views?

Upvotes: 0

Views: 1484

Answers (1)

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

You could pass additional data to the request body and decide which serializer to use. Here is an example.

def post(self, request, pk):
    if request.POST.get('is_opened'):
        serializer_class = OpenedQuestionSerializer
    else:
        serializer_class = ClosedQuestionSerializer

    serializer = serializer_class(data=request.data)
    if serializer.is_valid():
        serializer.save(exam=pk)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 3

Related Questions