python - 从 Django 中的请求获取错误消息

标签 python django http-status-code-403

如果用户访问不允许他访问的页面,我会尝试引发 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}}

最佳答案

Django 文档告诉我们,对于 403 错误,它会在这样的上下文中传递异常

return http.HttpResponseForbidden(
    template.render(request=request, context={'exception': force_text(exception)})
)

所以看来您应该能够仅使用 {{ exception }} 来访问异常的消息。否则,您可以覆盖默认的 403 View 并手动传递异常消息(甚至格式化它)。

关于python - 从 Django 中的请求获取错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33066540/

相关文章:

ruby-on-rails - OpenURI::HTTPError: 403 Forbidden

django - 如何在 Django 中创建自定义 403 页面?

Python+Pygame glibc错误

python - 更改 python 中的嵌套字典值

python - 在 Django 中限制暴力登录攻击

python - 在我的网络应用程序上使用 ubuntu 字体

python - 如何在 Python 中猴子修补 __init__ 模块?

php - 带有 php curl 的 HTTP 错误 403

python - matplotlib:如何清楚地显示所有特征(大约150个)

python - 让本地 numpy 覆盖全局