This peace of JS code can fix this, it will work for both Django and Jinja2,
because it is pure javaScript handling for post method form tags, you can customize it by explore it friends
I'm just getting the CSRF token from cookies which already always exist and use it in form tags
let 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;
}
$(()=>{
formTags = document.querySelectorAll('[method="POST"]')
let csrfToken = getCookie('csrftoken')
Array.from(formTags).forEach(formTag=>{
var inputTag = document.createElement('input')
inputTag.setAttribute('type', 'hidden')
inputTag.setAttribute('name', 'csrfmiddlewaretoken')
inputTag.setAttribute('value', [csrfToken])
formTag.appendChild(inputTag)
})
})