简体   繁体   中英

Django - Javascript - Csrf Token

This is the code I have attempted to try and add a csrf token to a javascript form.

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();
}

Can you see any problems with this? It has an error and therefore the JS does not run.

The {% csrftoken %} template tagoutputs the actual form tag (eg <input type='hidden' ... /> .

If you just want the value of the token, use {{ csrf_token }} instead.

If you are submitting the form with an ajax request, you might find it easier to send the CSRF token as a header, rather than adding the tag to your form. See the docs for instructions.

You have 2 errors in your code. Simple way look at code. Try it:

var i = document.createElement("input");
i.setAttribute('name', 'Score');
i.setAttribute('value', ""+score);
form.appendChild(i);
var i = document.createElement("input");
i.setAttribute('name', 'csrfmiddlewaretoken');
i.setAttribute('value', '{{ csrf_token }}');
form.appendChild(i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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