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:
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:
is_ajax = request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest"
Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 JavaScript
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.