Django 不使用 Ajax post 检查 csrf 令牌

Django doesn't check for a csrf token with Ajax post

根据 Django docs,Django 应该使用中间件默认启用 csrf 令牌验证。当我查看我的设置文件时,我确实看到包含了中间件。

但是,当我使用 Ajax 执行没有 csrf 令牌的 post 请求时,Django 将允许它。它不应该 return 一个错误说 csrf 令牌无效吗?我看到很多无法验证其 csrf 令牌的人提出的问题,但我无法使其无效。

这是我的 Ajax post 函数(我用 js 从我的输入中收集数据,并将其传递给这个函数):

function ajaxPost(url, data, success) {
fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(data),
    headers: new Headers({
        'Content-Type': 'application/json'
    })
}).then(res => res.json())
    .then(response => {
        if (response.status !== success) {
            //errors
        }
        updateView(response);
    })
    .catch(error => console.error('Error:', error))
}

这是我的视图函数:

@api_view(['POST'])
# API endpoint for posting bulk properties
def bulk(request):
    new_properties = []
    if request.method == 'POST':
        for obj in request.data:
            discipline = Discipline.objects.get(pk=obj['discipline.id'])
            root_function = Function.objects.get(pk=obj['root_function'])
            new_property = Property(name=obj['name'], value=obj['value'], unit=obj['unit'],
                                    discipline_id=discipline)
        new_property.save()
        new_property.function.add(root_function)
        new_properties.append(new_property)

    new_properties = json.loads(serializers.serialize('json', new_properties))

    return JsonResponse({'status': 201, 'new_properties': new_properties})

假设 api_view 是来自 django-rest-framework 的视图,它会禁用该视图的 CSRF 保护。

这是因为 API 端点经常用于没有 CSRF 令牌的外部请求;在这些情况下没有必要检查它。