[Django]-Django: How can I make views accept only ajax request?

4👍

Http404 is an exception, not a HttpResponse object so you should raise it instead of return:

raise Http404

Alternatively, you can return django.http.HttpResponseNotFound which has roughly the same effect as raising the above exception:

return HttpResponseNotFound("Page not found")

By the way, I would create a custom decorator that checks if the request is AJAX instead of polluting the view code with if/else clauses.

You can make use of method_decorator function to make the custom decorator work with class based views:

from django.utils.decorators import method_decorator

class CustomerInfoCheckView(View):
    @method_decorator(ajax_required)
    def post(self, request, *args, **kwargs):
        ...

Leave a comment