[Fixed]-DjangoRestFramework / Django Class Based Views โ€“ How to make it redirect to login page if 403 error is raised

1๐Ÿ‘

โœ…

You can add the TemplateHTMLRenderer to your view renderer_classes, this will enable you to use the django 403.html template when an user goes to the url and the user is not authenticated. http://www.django-rest-framework.org/api-guide/renderers/#templatehtmlrenderer

class user_detail(APIView):
    """
    Get, update or delete a specific user.
    """
    permission_classes = (IsAuthenticated,)
    # Add TemplateHTMLRenderer to your view renderer_classes
    renderer_classes = (JSONRenderer, TemplateHTMLRenderer)

    def get_object(self, pk):
        try:
            return User.objects.get(pk=pk)
        except User.DoesNotExist:
            raise Http404

    def get(self, request, pk):
        user = self.get_object(pk)
        serializer = UserSerializer(user)
        return Response(serializer.data)
๐Ÿ‘คPieter Hamman

Leave a comment