Search code examples
pythondjangodjango-rest-frameworkdjango-generic-viewsdjango-quiz

Adding a redirect to CreateAPIView


I want to redirect the user to the AddQuestionsView after the user creates a quiz(after adding title).

My CreateQuiz

class CreateQuizzView(CreateAPIView):
    serializer_class = CreateQuizSerializer

My serializers.py file

class CreateQuizSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quizzer
        fields = ['title']

    def create(self, validated_data):
        user = self.context['request'].user
        new_quiz = Quizzer.objects.create(
            user=user,
            **validated_data
        )
        return new_quiz

Can i add redirect by adding any Mixin or change need to change the GenericView.


Solution

  • An APIView is normally not used by a browser, or at least not directly, hence a redirect makes not much sense. The idea is that some program makes HTTP requests, and thus retrieves a response. Most API handlers will not by default follow a redirect anyway.

    You can however make a redirect, by overriding the post method:

    from django.shortcuts import redirect
    
    class CreateQuizzView(CreateAPIView):
        serializer_class = CreateQuizSerializer
    
        def post(self, *args, **kwargs):
            super().post(*args, **kwargs)
            return redirect('name-of-the-view')