[Django]-Redirect after POST django rest framework

39👍

viewsets.ModelViewSet has a method create that returns Response object. The response object is subtype of Django Response. Hence you can change behavior using HttpResponseRedirect into the create method. For example:

class entry_ViewSet(viewsets.ModelViewSet):
    queryset = Entry.objects.all()
    serializer_class= EntrySerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)

    def create(self, request, *args, **kwargs):
        response = super(entry_ViewSet, self).create(request, *args, **kwargs)
        # here may be placed additional operations for
        # extracting id of the object and using reverse()
        return HttpResponseRedirect(redirect_to='https://google.com')

    def perform_create(self, serializer):
        serializer.partial = True
        serializer.save(created_by=self.request.user)

Leave a comment