[Answered ]-Django4: Ajax AttributeError

1👍

here is a way to implement is_ajax to every request:

  1. create a middlewares.py in any of your app, in my case, common app. (it does not matter which app you add this in, middlewares are wrapper functions called globally to perform action before or after view).

class AjaxMiddleware:
def init(self, get_response):
self.get_response = get_response

    def __call__(self, request):
        def is_ajax(self):
            return request.META.get('HTTP_X_REQUESTED_WITH') == 
                   'XMLHttpRequest'
        
        request.is_ajax = is_ajax.__get__(request)
        response = self.get_response(request)
        return response

this will define a is_ajax method on every request before it is received by the view.

  1. plug this in settings.py:

    MIDDLEWARE = [
    ‘common.middleware.AjaxMiddleware’,
    ]

And this will solve your error.

0👍

Ok, seems to be working now. request.is_ajax is deprecated since django 3.1 and has been removed since django 4

if request.headers.get('x-requested-with') == 'XMLHttpRequest': 

instead of

if request.is_ajax:
👤a56z

Leave a comment