如何在没有ajax的情况下使用js在django中添加csrf令牌?

时间:2017-12-19 05:14:29

标签: javascript python json django

我基本上想要实现一个接受一些json数据的django视图,然后发布一个将显示的json数据。确认组视图通过json数据接受一个人列表,组成一个组,然后返回组代码回到展示。

我收到了Forbidden(403)CSRF令牌丢失或错误错误

我是django和js的初学者,所以请相应地回答。提前感谢你:))

view.py

def confirm_group(request):
    data = json.loads(request.body.decode("utf-8"))
    grp = Group()
    grp.group_code = group_code_generator()
    grp.save()
    for i in range(len(data)):
        Player = Regplayer.objects.filter(pk=data[i]["pk"])
        pl = Enteredplayer()
        pl.regplayer = Player
        pl.group = grp
        pl.save()
    return JsonResponse(grp.group_code, safe=False)

的script.js

function confirm()
{
    var i = 0;
    var rows= document.getElementById("group").children;
    var num= document.getElementById("group").childElementCount;
    if(num==0)
    {

    }
    else
    {
//      alert("Confirm grouping of "+num+" people?");
        for(i=0; i < num; i++)
        {
            send_name=rows[i].children[0].children[0].innerHTML;
            send_gender=rows[i].children[3].children[0].innerHTML;
            send_clgname=rows[i].children[1].children[0].innerHTML;
            send_sport=rows[i].children[2].children[0].innerHTML;
            send_id=rows[i].children[5].innerHTML;
            myObj["data"].push({"name":send_name, "gender":send_gender, "college":send_clgname, "sport": send_sport, "pk": send_id});
            alert(JSON.stringify(myObj));
        }
        csrf_token = document.getElementById('csrf_token').innerHTML;
        myObj["data"].push({"csrfmiddlewaretoken": csrf_token });

        //POST TO BACKEND
                    // Sending and receiving data in JSON format using POST method
        //
            var ourRequest = new XMLHttpRequest();
            var url = "/confirm_group/";
            ourRequest.open("POST", url, true);
            ourRequest.setRequestHeader("Content-type", "application/json");
            // POST 
            var data = JSON.stringify(myObj);
            ourRequest.send(data);
            // Obtain 
            ourRequest.onreadystatechange = function () {
                if (ourRequest.readyState === 4 && ourRequest.status === 200)     {
                    var json = JSON.parse(ourRequest.responseText);
                    var groupCode = json.groupcode;
                    //json object received
                    new_group(groupCode);
                }
            };
        // if success call new_group() else call error_handle()
//        new_group();  
        //error_handle();
        //empty json object now

    } 
}

的index.html

<span id="csrf_token" style="display: none;">{{ csrf_token }}</span>
    <div class="confirm-modal">
      <div class="form">
        <p id="modal-text"></p>
        <button class="btn1" onclick="confirm()">Confirm</button>
        <button class="btn2" onclick="close_modal()">Cancel</button>
      </div>
    </div>

0 个答案:

没有答案