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

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

我试图在 Django 中学习 ajax 但是当我 运行 这个简单的测试时我得到了这个错误而且我找不到原因, 我的 Django 版本是 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>

来自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.

即使它已被弃用,您也可以创建一个自定义函数来检查请求类型,

def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

并在您认为的任何地方使用,

from django.shortcuts import HttpResponse


def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'


def ajax_test(request):
    if <b>is_ajax(request=request)</b>:
        message = "This is ajax"
    else:
        message = "Not ajax"
    return HttpResponse(message)

根据 release notes of 3.1

完成 JPG 答案

request.is_ajax() can be reproduced exactly as request.headers.get('x-requested-with') == 'XMLHttpRequest'

Django使用的requestobject类似于requests。当您的客户端使用特定的 header x-requested-withXMLHttpRequest.

时,您可以识别 AJAX 请求