Django-Javascript-Csrf令牌

Django-Javascript-Csrf令牌,javascript,django,python-3.x,post,csrf,Javascript,Django,Python 3.x,Post,Csrf,这是我尝试向javascript表单添加csrf令牌的代码 function save() { var form = document.createElement("form"); console.log(form); form.setAttribute('method', 'post'); form.setAttribute('action', '/quiz_score/'); document.body.appendChild(form); v

这是我尝试向javascript表单添加csrf令牌的代码

function save() {
    var form = document.createElement("form");
    console.log(form);
    form.setAttribute('method', 'post');
    form.setAttribute('action', '/quiz_score/');
    document.body.appendChild(form);
    var i = document.createElement("input");
    i.setAttribute('name', 'Score');
    i.setAttribute('value', ""+score);
    i.setAttribute('name', 'csrfmiddlewaretoken');
    i.setAttribute('value', {% csrftoken %});
    form.appendChild(i);
    form.submit();
}

你觉得这有什么问题吗?它有一个错误,因此JS不会运行。

模板标记输出实际的表单标记(例如

如果您只需要令牌的值,请使用
{{{csrf_token}}


如果您使用ajax请求提交表单,您可能会发现将CSRF标记作为标头发送比将标记添加到表单更容易。有关说明,
{%csrftoken%}
模板标记输出实际的表单标记(例如

如果您只需要令牌的值,请使用
{{{csrf_token}}


如果您在提交带有ajax请求的表单,您可能会发现将CSRF令牌作为标头发送比将标记添加到表单更容易。有关说明。

您的代码中有两个错误。简单方法查看代码。 试试看:

var i=document.createElement(“输入”);
i、 setAttribute('name','Score');
i、 setAttribute('值',''+分数);
表格二(i);
var i=document.createElement(“输入”);
i、 setAttribute('name','csrfmiddlewaretoken');
i、 setAttribute('value','{csrf_token}}');
表格二(i);

您的代码中有两个错误。查看代码的简单方法。 试试看:

var i=document.createElement(“输入”);
i、 setAttribute('name','Score');
i、 setAttribute('值',''+分数);
表格二(i);
var i=document.createElement(“输入”);
i、 setAttribute('name','csrfmiddlewaretoken');
i、 setAttribute('value','{csrf_token}}');
表格二(i);