Skip to content

Instantly share code, notes, and snippets.

@tinshade
Last active June 24, 2021 09:53
Show Gist options
  • Save tinshade/da96b73753e6e0a664e8467e7b7f0b58 to your computer and use it in GitHub Desktop.
Save tinshade/da96b73753e6e0a664e8467e7b7f0b58 to your computer and use it in GitHub Desktop.
Getting CSRF for Django from JS. Just include this script in the HEAD section.
function getToken(name) {
let user = '{{request.user}}'
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const 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 csrftoken = getToken('csrftoken');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment