Created
November 7, 2017 15:25
-
-
Save sirodoht/fb7a6e98d33fc460d4f1eadaff486e7b to your computer and use it in GitHub Desktop.
Get CSRF token from Django HTML templates with vanilla JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getCsrf() { | |
var inputElems = document.querySelectorAll('input'); | |
var csrfToken = ''; | |
for (i = 0; i < inputElems.length; ++i) { | |
if (inputElems[i].name === 'csrfmiddlewaretoken') { | |
csrfToken = inputElems[i].value; | |
break; | |
} | |
} | |
return csrfToken; | |
}; |
Thanks, I'm really glad that I got the above two methods.
Below is django's way of getting csrf_token value in vanilla js which has been mentioned in the official docs reference
// In your js file you can include this code block
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrf_token = getCookie("csrftoken");
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As a small note for others getting here from google, another way of getting the csrf token is by doing
Django will inject the csrf token without any html, so you can use that variable in any embedded or included Javascript.