1

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.

2 Answers 2

3

The {% csrftoken %} template tagoutputs the actual form tag (e.g. <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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.