简体   繁体   English

禁止(CSRF 令牌丢失或不正确。) | Django 和 AJAX

[英]Forbidden (CSRF token missing or incorrect.) | Django and AJAX

:( :(

I am making ajax requests, but I get this error:我正在发出 ajax 请求,但出现此错误:

Forbidden (CSRF token missing or incorrect.): /manager/ajax/
[23/Jun/2020 00:00:46] "POST /manager/ajax/ HTTP/1.1" 403 2517
[23/Jun/2020 00:01:18] "GET /manager/test/update/3/ HTTP/1.1" 200 10249
Forbidden (CSRF token missing or incorrect.): /manager/ajax/
[23/Jun/2020 00:01:18] "POST /manager/ajax/ HTTP/1.1" 403 2517
[23/Jun/2020 00:01:22] "GET /manager/test/update/3/ HTTP/1.1" 200 10249
Forbidden (CSRF token missing or incorrect.): /manager/ajax/
[23/Jun/2020 00:01:23] "POST /manager/ajax/ HTTP/1.1" 403 2517

JS: JS:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

fetch('/manager/ajax/', {
    method: 'POST',
    body: JSON.stringify({
        csrfmiddlewaretoken: csrftoken,
        title: 'hello!!!! :(',
    }),

    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
})
.then(response => response.json())
.then(json => console.log(json))

My view:我的观点:

def delete_exam_question(request):
    print(request.method)

    if request.is_ajax:
        print(request.POST)
        #exam_question = ExamQuestion.objects.get(title = request.POST.get('title'))
        #exam_question.delete()

    return JsonResponse({'deleted': True})

I tried to fix it like in this question ( "application/x-www-form-urlencoded" ), I already tried indicating "application/json" , but it does not work... :(我试图像在这个问题"application/x-www-form-urlencoded" )中那样修复它,我已经尝试过指示"application/json" ,但它不起作用...... :(

I pass the token ( csrftoken ), but it still doesn't work, I've tried everything, but I can't get it to work.我通过了令牌( csrftoken ),但它仍然不起作用,我已经尝试了一切,但我无法让它工作。


UPDATE:更新:

( "Content-Type" => "application/x-www-form-urlencoded" ) "Content-Type" => "application/x-www-form-urlencoded"

Decorate the view, with the decorator csrf_exempt .使用装饰器csrf_exempt装饰视图。 And the POST data are: POST数据是:

<QueryDict: {'{"csrfmiddlewaretoken":"4gTL9H17LIgTFc3HseYFuT6JQMbkEHxiuGXVxu9WWKTgN0gVmUtJJPDgwem0zj4U","title":"holaaa"}': ['']}>

That's why he gave me the error, but this, is very very rare.这就是他给我错误的原因,但这种情况非常罕见。 And I don't know how to correct it, any ideas?而且我不知道如何纠正它,有什么想法吗? I don't know much JavaScript.我不太了解JavaScript。

I changed the Conten-Type , to "application/json" , and the POST data are:我将Conten-Type更改为"application/json" ,POST 数据为:

<QueryDict: {}>

but, i print request.body , and printed that:但是,我打印request.body ,并打印:

b'{"csrfmiddlewaretoken":"4gTL9H17LIgTFc3HseYFuT6JQMbkEHxiuGXVxu9WWKTgN0gVmUtJJPDgwem0zj4U","title":"holaaa"}'

what's going on?这是怎么回事? :( :(

Take a look of the source code below, you need explicitly tell Django this request if called using XMLHttpRequest .看看下面的源代码,如果使用XMLHttpRequest调用,您需要明确告诉 Django 这个请求。 better avoid to use is_ajax to detect ajax, since it will be deprecated in future versions最好避免使用is_ajax来检测 ajax,因为它将在未来的版本中被弃用

def is_ajax(self):
    warnings.warn(
        'request.is_ajax() is deprecated. See Django 3.1 release notes '
        'for more details about this deprecation.',
         RemovedInDjango40Warning,
         stacklevel=2,
      )
     return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

Add these lines in your header, use of X-CSRFToken is prefered for ajax request since it also support other request method like DELETE , PUT , etc在您的 header 中添加这些行,对于 ajax 请求,首选使用X-CSRFToken ,因为它还支持其他请求方法,如DELETEPUT

# django internllay change '-' to '_' and add prefix HTTP in front of the value
# so 'X-Requested-With' becomes HTTP_X_REQUESTED_WITH, which is used by is_ajax function 
{
   'X-Requested-With': 'XMLHttpRequest',
   'X-CSRFToken': <your_csrftoken_value>
}

EDIT编辑

$('#sub-btn').click(function(e){ 
    e.preventDefault();
    $.ajax( 
        { 
        type:"POST", 
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('X-CSRFToken', <your_csrftoken_value>);
        },
        url: <your_url>, 
        data: {test: 'test'},
        success: function(data){ 
           console.log(data)
        }
    });
})  

Also, if you use jQuery and send data using this format, you could receive data in request.POST此外,如果您使用jQuery并使用此格式发送数据,您可以在request.POST中接收数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Django 中的 ajax POST 期间禁止(CSRF 令牌丢失或不正确。) - Forbidden (CSRF token missing or incorrect.) during ajax POST in Django “禁止(CSRF 令牌丢失或不正确。):”使用 Django 和 JS - “Forbidden (CSRF token missing or incorrect.):” using Django and JS Django 和 Axios 禁止访问(CSRF 令牌丢失或不正确。) - Django and Axios Forbidden (CSRF token missing or incorrect.) (缺少CSRF令牌或不正确。)在Django中使用AJAX - (CSRF token missing or incorrect.) using AJAX in Django 尽管正确发送令牌,Django 服务器仍报告“禁止(CSRF 令牌丢失或不正确。)”? - Django server reporting "Forbidden (CSRF token missing or incorrect.)" despite sending token correctly? 错误:使用 django rest 框架时禁止(CSRF 令牌丢失或不正确。) - Error :Forbidden (CSRF token missing or incorrect.) while using django rest framework 禁止(CSRF令牌丢失或不正确。)-即使已包含 - Forbidden (CSRF token missing or incorrect.) - even though it's included 禁止(CSRF令牌丢失或不正确。)Django如何解决?用我的代码 - Forbidden (CSRF token missing or incorrect.) Django how to solve?WITH MY CODE 如何更正 django 中的以下代码,它给出错误“禁止(CSRF 令牌丢失或不正确。)” - How do I correct the following code in django, It's give an error “Forbidden (CSRF token missing or incorrect.)” 用yui设置Django CSRF_TOKEN,但控制台显示“ django.request禁止(CSRF令牌丢失或不正确。)”。 - Set Django CSRF_TOKEN with yui, but console says 'django.request Forbidden (CSRF token missing or incorrect.)'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM