Manasvi Batra Manasvi Batra - 7 months ago 39
Python Question

Django HttpResponseRedirect not working in custom permission (authentication.py)

I have created a custom permission which checks a user is logged in. I check it through a token, if token does not exists, it is not logged in and therefore it should be redirected to the homepage. I have imported all the necessary requirements like HttpResponseRedirect and other things. This is used as permission_class in my viewset (where in some methods I render response as html template and somewhere as json). Here goes the code:

class AccountPermission(permissions.BasePermission):
message = "Not a valid customer"

def has_permission(self, request, view):
if not token:
return HttpResponseRedirect('/')
else:
return True


The problem is the Viewset considers the HttpResponseRedirect html from custom permission as True and allows the user to use methods in the Viewset. How can this be avoided?

Answer

Hey I found the solution. It would be helpful if anyone needs this in future. I created an exception handler for rest framework exceptions and initiated in settings.py file:

REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'app_name.exception.function_name'
}

I created my exception handler function custom_exception_handler in exception.py :

from rest_framework.views import exception_handler
from django.http import HttpResponseRedirect

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response is not None and response.status_code == 403:
        return HttpResponseRedirect("/")
else:
    return response