Home > Net >  AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'

Time:12-20

im trying to learn ajax in django but when i running this simple test i got this error and i cant find the reason, my django version is 4.0

AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'

view.py

from django.shortcuts import render, HttpResponse
def home(request):
    return render(request,'myapp/index.html')

def ajax_test(request):
    if request.is_ajax():
        message = "This is ajax"
    else:
        message = "Not ajax"
    return HttpResponse(message)

urls.py

urlpatterns = [
    path('',views.home,name='home'),
    path('ajax_test/', views.ajax_test, name='ajax_test')
]

index.html

<button id="btn">click me!</button>
   

<script>
  $("#btn").click(function () {
    $.ajax({
      type: "GET",
      url: "{% url 'ajax_test' %}",

      success: function () {
        console.log("done");
      },
      error: function () {
        console.log("error");
      },
    });
  });
</script>

CodePudding user response:

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.

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)
  • Related