Skip to content

Instantly share code, notes, and snippets.

@sirodoht
Created November 7, 2017 15:25
Show Gist options
  • Save sirodoht/fb7a6e98d33fc460d4f1eadaff486e7b to your computer and use it in GitHub Desktop.
Save sirodoht/fb7a6e98d33fc460d4f1eadaff486e7b to your computer and use it in GitHub Desktop.
Get CSRF token from Django HTML templates with vanilla JS
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;
};
@max-cool
Copy link

max-cool commented Jul 28, 2020

As a small note for others getting here from google, another way of getting the csrf token is by doing

<script>
    var csrf = "{{ csrf_token }}"
</script>

Django will inject the csrf token without any html, so you can use that variable in any embedded or included Javascript.

@sudocodedev
Copy link

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