Last active
June 24, 2021 09:53
-
-
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.
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 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