I want to show an informative error message to a user hitting a page that results in a 403 Forbidden. I'm using Django 1.8.
My idea of passing an error message is this:
# in a view
if not ...:
raise PermissionDenied('You have no power here')
Then somewhere in the handler403
view, I'd like to retrieve the message (or maybe even a structured object) and render an informative page based on it.
Though the handler seems to only receive the request object and the template name.
Is there a way to pass a custom message to the handler? (Of course I could assign a custom attribute to the request object before raising the exception, and hope that the same object will be passed to the handler, but this feels like a hack.)
Update: Indeed there is a middleware for that already: contrib/messages
is capable of piggybacking messages on the request object, and more.
答案 0 :(得分:1)
看起来你必须使用中间件来实现它:
class ExceptionMiddleware:
def process_exception(self, request, exception):
if exception.args:
request.message = exception.args[0]
然后在您的handler403
中,您可以访问request.message
。
显然,你可以充实这个中间件,允许传递的信息不仅仅是一条消息。