HttpRequest.is_ajax()
is deprecated starting with version 3.1.
I want to return html if the page is requested from a browser and as JsonResponse
if called from javascript or programmatically.
I am seeking guidance on how to do that.
https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest.is_ajax
Check HTTP_X_REQUESTED_WITH
header
def sample_view(request):
is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
From the Release Notes of 3.1
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 newHttpRequest.accepts()
method if your code depends on the client Accept HTTP header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With