所以我试图用AJAX而不是Django来处理GET请求所以当403 Forbidden(由Django给出)被引发时,我可以用jQuery显示一个简单的弹出/模态,但我不知道如何继续
这是我处理请求的Javasscript:
只需在我的html中获取一个按钮,然后等待Click事件。
$(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);
},
});
});
});
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)
所以现在,如果我是超级用户,我会被重定向到我想要的页面,但我希望能够基本向用户显示一条消息(弹出窗口或模态),说他们没有权限,如果Django引发了PermissionForbidden。
另外,我不希望在发生这种情况时刷新页面,或者Chrome控制台显示403 Forbidden Message。
我不知道它是否真的需要很多/如果它很长,但要提前感谢任何建议/提示。
答案 0 :(得分:1)
您应该能够在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
...