简体   繁体   English

403 FORBIDDEN使用ajax发送帖子DJANGO

[英]403 FORBIDDEN use ajax to send post DJANGO

I use Ajax for send in POST data to view of Django but I have this error : 403 FORBIDDEN. 我使用Ajax发送POST数据以查看Django,但出现此错误:403 FORBIDDEN。

Actually, I use @csrf_exempt but I'm affraid isn't the better idea... 实际上,我使用@csrf_exempt,但我不认为这不是更好的主意...

My view : 我的观点 :

@csrf_exempt
def myfic(request):
    if request.method == "POST" :
        competences = request.POST.get('theCompetences')
        print("competences : ",competences)
    ...

My code JS : 我的代码JS:

function envoie_post_competences(){
    $.post("http://localhost:8000/myfic",{theCompetences:"aaaaaaa",});
    return false;
}

What's the better solution ? 有什么更好的解决方案?

Thank you for your help ! 谢谢您的帮助 !


So just i must add this code : 因此,我必须添加以下代码:

var csrftoken = $.cookie('csrftoken');

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

and my function JS not changed ? 和我的功能JS不变吗?

function envoie_post_competences(){
    $.post("http://localhost:8000/myfic",{theCompetences:"aaaaaaa",});
    return false;
}

If yes, when I click on submit button, nothing is happening.. 如果是,当我单击“提交”按钮时,没有任何反应。

您需要设置X-CSRFToken标头,如文档中所示。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM