如何使用 Ajax 从 Django 捕获 PermissionDenied(403)?

How to catch a PermissionDenied(403) from Django with Ajax?

所以我尝试使用 AJAX 而不是 Django 来处理 GET 请求,这样当出现 403 Forbidden(由 Django 提供)时,我可以用 jQuery 显示一个简单的 pop-up/modal ,但是我现在不确定如何继续。

这是我处理请求的 Javasscript:

刚在我的 html 中获取一个按钮并等待 Click 事件。

main.js

$(document).ready(function(){
  $("#users_page").click(function(e){
    e.preventDefault();
    $.ajax({
      "method": "GET",
      "url": "/dashby/users/",
      "beforeSend": function(xhr, settings){
        console.log("Before send");
      },
      "success": function(result){
        window.location.href = "/dashby/users/";
      },
      "error": function(xhr, textStatus, error){
        console.log(error);
      },
    });
  });
});

我的view.py对于这件事

class AllUsersViews(UserPassesTestMixin, View):
    template_name = 'all_users.html'
    raise_exception = True # Raise PermissionDenied(403)

    def test_func(self):
        #Only superusers can access this view.
        if self.request.user.is_superuser:
            return True

    def get(self, request):
        context = {'users': User.objects.all()}
        return render(request, self.template_name, context)

所以现在,如果我是超级用户,我确实会被重定向到我想要的页面,但我希望能够向用户显示一条消息(弹出窗口或模式),说他们没有如果 PermissionForbidden 由 Django 引发,则许可。

此外,我不希望页面在发生这种情况或 Chrome 控制台显示 403 禁止消息时刷新。

我不知道这是否真的有很多问题要问/它是否很长但是感谢提前advice/tips。

您应该能够在 error 处理程序中看到 HTTP 错误:

$.ajax({
    ...
    error: function (xhr, ajaxOptions, thrownError) {
        if(xhr.status==403) {
            alert(...);
        }
    }
}

您将始终在控制台中看到 403,因为这是您从服务器获得的 HTTP 响应。

您可以将 test_func 简化为:

class AllUsersViews(UserPassesTestMixin, View):
    ...

    def test_func(self):
        return self.request.user.is_superuser

    ...