user3595632 user3595632 - 1 month ago 9
Ajax Question

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

What I want to do is not to allow general POST request, only accept

ajax
request.

class CustomerInfoCheckView(View):

def post(self, request, *args, **kwargs):
# CustomerInfoForm by ajax request
if request.is_ajax():
form = CustomerInfoForm(
request.POST,
)

if form.is_valid():
return JsonResponse(
data={
"valid": True,
}
)
else:
return JsonResponse(
data={
"valid": False,
"errors": form.errors
}
)
else:
return Http404


But problem is that is shows an error:
AttributeError: type object 'Http404' has no attribute 'get'
.

How can I deal with it?

Answer

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

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):
        ...