45👍
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.
Even though it has been deprecated, you can create a custom function to check the request type as,
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
and use anywhere in your view as,
from django.shortcuts import HttpResponse
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def ajax_test(request):
if is_ajax(request=request):
message = "This is ajax"
else:
message = "Not ajax"
return HttpResponse(message)
16👍
this method should not be removed, since jQuery the most underrated library, still surviving, strongly, in many modern tutorials. hope one day they will bring it back.
And I found it weird for same version of django, after server deployment this error was reported, but never in local machine.
if you have implemented is_ajax
in your project, and it is largely scoped, here is a way to implement is_ajax
to every request
- create a
middlewares.py
in any of your app, in my case,common
app. (it does not matter which app you add this in, middlewares are wrapper functions called globally to perform action before or after view)
class AjaxMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
def is_ajax(self):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
request.is_ajax = is_ajax.__get__(request)
response = self.get_response(request)
return response
this will define a is_ajax
method on every request before it is received by the view.
- plug this in
settings.py
:
MIDDLEWARE = [
'common.middlewares.AjaxMiddleware',
]
- [Django]-NoReverseMatch at /rest-auth/password/reset/
- [Django]-How to use curl with Django, csrf tokens and POST requests
- [Django]-Django Reverse Query in Template
10👍
To complet the JPG answer based on the release notes of 3.1
request.is_ajax() can be reproduced exactly as request.headers.get(‘x-requested-with’) == ‘XMLHttpRequest’
The request
object used by Django is like requests. You can identify an AJAX request when your client use the specific header x-requested-with
set with XMLHttpRequest
.
- [Django]-Django: multiple models in one template using forms
- [Django]-How to do reverse URL search in Django namespaced reusable application
- [Django]-How can I test https connections with Django as easily as I can non-https connections using 'runserver'?