Django How to check a request is Ajax
Asked Answered
H

2

6

The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.

Hiragana answered 14/2, 2022 at 5:38 Comment(1)
what is the actual question being asked?Birk
I
7
def is_ajax(request):
  return request.headers.get('x-requested-with') == 'XMLHttpRequest'
Inconsistent answered 14/2, 2022 at 5:45 Comment(0)
H
4

If you are writing your own AJAX detection method, request.is_ajax() can be reproduced exactly as

if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
    is_ajax = True
else:
    is_ajax = False
Hiragana answered 14/2, 2022 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.