django 不呈现自定义 403 页面,而是显示浏览器默认值

django not rendering custom 403 page, displays browser default instead

我正在尝试应用自定义 403 模板来显示,而不是浏览器默认模板。

我有一个看起来像这样的中间件:

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',
]

我在上面处理 404 错误的相同过程,但出于某种原因,我无法让它处理 403 错误。

您正在此处返回回复:

return HttpResponseForbidden()

这本身就是一个回应,不会使用handler403。如果你想使用错误处理视图,你应该 引发 异常:

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:
                <b>raise PermissionDenied()</b> # raise an exception
        response = self.get_response(request)
        return response