Piero Marini Piero Marini - 2 months ago 12
Javascript Question

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

So im trying to handle a GET request with AJAX instead of Django so I can display a simple pop-up/modal with jQuery when a 403 Forbidden (Given by Django) is raised, however im not sure how to continue right now.

This is my Javasscript that handles the request:

Just gets a button in my html and waits for Click event.

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);
},
});
});
});


my view.py for this matter



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)


So right now if im a superuser i do get redirected to the page I want but I want to be able to basically display a message to the user (A pop-up or a modal) saying that they do not have permission if the PermissionForbidden is raised by Django.

Also, I dont want the page to refresh when this happens or that the Chrome Console displays the 403 Forbidden Message.

I dont know if it's actually a lot to ask/ if its long but thanks to any advice/tips in advance.

Answer

You should be able to see HTTP errors in the error handler:

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

You will always see the 403 in the console as that's the HTTP response you are getting from the server.

You can simplify the test_func to just:

class AllUsersViews(UserPassesTestMixin, View):
    ...

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

    ...