About Ajax Calls using Fetch API

If you are using fetch API and want request.is_ajax() to recognize the Ajax call, then pass X-Requested-With: XMLHttpRequest header from the fetch call:

1
2
3
4
5
6
7
8
let form = document.getElementById('comment_form');
fetch(form.getAttribute('action'), {
    method: 'POST',
    body: new FormData(form);,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
    },
});

On the other hand, request.is_ajax() has been deprecated since Django 3.1, but you can still get the same information in the view as follows:

1
is_ajax = request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest"

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 JavaScript