如果用户访问不允许访问的页面,我尝试引发403错误。在我的 views.py
中def staff_room(request):
user = request.user
role = School.objects.get(user=user)
if not role.is_teacher:
raise PermissionDenied("Get out of the staff room!")
def library(request):
user = request.user
role = School.objects.get(user=user)
if not role.is_librarian:
raise PermissionDenied("Get out of the library!")
在我的 403.html 中,我想检索错误引发的不同消息。有办法吗?像{{ exception.message }}
之类的东西就像说
{% extends 'base.html' %}
You are not allowed to enter this room. {{ exception.message}}
答案 0 :(得分:3)
Django文档告诉我们,对于403错误,它在上下文中传递异常,如此
return http.HttpResponseForbidden(
template.render(request=request, context={'exception': force_text(exception)})
)
因此,您似乎应该只能使用{{ exception }}
来访问异常消息。否则,您可以覆盖默认的403视图并手动传递异常消息(甚至格式化)。