【问题标题】:Custom 403 error page in django rest frameworkdjango rest框架中的自定义403错误页面
【发布时间】:2019-02-22 14:17:29
【问题描述】:

我正在尝试通过在 ulrs.py handler403 = 'my_app.views.handler403' 中声明来覆盖 django rest 框架的默认 403.html 模板。

在应用的views.py中:

def handler403(request, exception, template_name='403.html'):
    response = render_to_response('403.html', {})
    response.status_code = 403
    return response

模板的目录包含在 settings.py 的 TEMPLATE_DIRS 中。 但是,向具有 IsAdminUser 权限的端点发出请求会呈现默认的 drf 模板。

针对 404 异常的完全相同过程工作得非常好。

我在网上看到的任何答案都没有帮助我解决问题。

【问题讨论】:

    标签: django django-rest-framework django-templates http-status-code-403


    【解决方案1】:

    其实很简单:

    您必须像下面这样覆盖 DRF 的“custom_exception_handler”:

    from Django.shortcuts import render_to_response
    
    def custom_exception_handler(...):
        response = render_to_response('path/to/template/403.html', {})
        response.status_code = 403
        return response
    

    【讨论】:

      【解决方案2】:

      它不起作用,因为 DRF 返回一个 json 响应,不呈现模板。

      【讨论】:

      • 那么我的问题有什么解决办法吗?
      • 视情况而定,你真的想在你的 api 中返回一个 HTML 响应而不是 JSON 响应吗?
      • 是的,当出现 403 时我想渲染一个自定义模板
      • 好的,按照这个答案softwareengineering.stackexchange.com/a/344112 我想如果你分享你的观点,我可以帮助你。请使用您的查看代码 sn-p 编辑您的问题。
      【解决方案3】:

      试试这个:

      from django.shortcuts import render
      def handler403(request, exception, template_name='403.html'):
          return render(request, '403.html')
      

      【讨论】:

        猜你喜欢
        • 2012-01-31
        • 2016-05-03
        • 1970-01-01
        • 1970-01-01
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 2021-05-30
        • 1970-01-01
        相关资源
        最近更新 更多