Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django >= 3.1 and is_ajax

Tags:

ajax

django

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

like image 403
Vishal Avatar asked Aug 28 '20 08:08

Vishal


1 Answers

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 new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.

like image 77
JPG Avatar answered Oct 17 '22 05:10

JPG