1

I am trying to apply a custom 403 template to display instead of the browser default.

I have a Middelware that looks something like this:

from django.http import HttpResponseForbidden

class CheckUserTypeMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated:
            allowed_types = ['a', 'b', 'c', 'd', 'e']
            user_data = get_some_AD_values
            if user_data.get('a_key') not in allowed_types:
                return HttpResponseForbidden()
        response = self.get_response(request)
        return response

views.py

def error_403(request, exception):
    return render(request, 'my_app/403.html') # I have a 404.html in the same folder as the 403 and that renders fine.

urls.py

handler403 = 'my_app.views.error_403'

settings.py

DEBUG = False

MIDDLEWARE = [
    # Default Django middlewares untouched
    'my_app.middleware.my_middleware.CheckUserTypeMiddleware',
]

The same process I have above worked for 404 errors, but for some reason, I cant get it to work with 403 errors.

hello
  • 1,168
  • 4
  • 24
  • 59

1 Answers1

2

You are returning a response here:

return HttpResponseForbidden()

This is a response in itself and would not use the handler403. If you want the error handling views to be used you should raise an exception instead:

from django.core.exceptions import PermissionDenied

class CheckUserTypeMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated:
            allowed_types = ['a', 'b', 'c', 'd', 'e']
            user_data = get_some_AD_values
            if user_data.get('a_key') not in allowed_types:
                raise PermissionDenied() # raise an exception
        response = self.get_response(request)
        return response
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33