django - 我如何在 django 中提出禁止响应

标签 django

我想做以下事情:

raise HttpResponseForbidden()

但是我得到了错误:

exceptions must be old-style classes or derived from BaseException, not HttpResponseForbidden

我应该怎么做?

最佳答案

如果你想抛出异常,你可以使用:

from django.core.exceptions import PermissionDenied

def your_view(...):
    raise PermissionDenied()

记录在这里:

https://docs.djangoproject.com/en/stable/ref/views/#the-403-http-forbidden-view

与返回 HttpResponseForbidden 相反,引发 PermissionDenied 会导致使用 403.html 模板呈现错误,或者您可以使用中间件显示自定义“禁止” View 。

关于django - 我如何在 django 中提出禁止响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6618939/

相关文章:

python - 如何在 Django 中编写单元测试

python - django 创建自定义 shell 命令以创建具有自定义布局的应用程序

python - 属性错误: Generic detail view must be called with either an object pk or a slug

python - Django-cron 不执行作业

django - 如何将 Django 控制台的所有日志写入自定义文件?

python - 如何在每个月底运行 Celery 定期任务

python - 如何在 Django Rest Framework 中将数组序列化为字符串?

python - Django 多个外键 - 在详细信息管理页面中显示相关字段以进行添加/编辑

python - 我无法从 POSTMAN 进行 POST 调用,但可以手动进行 - Django

mysql - Django:将两个查询(两个不同模型)中的项目组合在一起