Currently, I am attempting to insert a form into an HTML page using JavaScript, similar to the {% csrf_token %} token that is automatically added when the page loads:
table += "<td><form action='' method='post'>";
table += "<input type='submit' value='Delete?' />";
table += "</form></td>;
$("#tbody").append(table);
The issue I am facing is receiving a CSRF validation error:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
I have attempted to include a custom CSRF token:
var buf = new Uint8Array(1);
window.crypto.getRandomValues(buf);
table += "<input type='hidden' name='csrfmiddlewaretoken' value='" + buf[0] + "'>";
However, this approach still results in an error.
In addition, my JavaScript file contains the following code snippet obtained from the Django website, though I am unsure of its functionality:
//enable csrf post ajax
//This function gets cookie with a given name
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 = jQuery.trim(cookies[i]);
// 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;
}
var csrftoken = getCookie('csrftoken');
/*
The functions below will create a header with csrftoken
*/
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain &&
(!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url)))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
My question is whether it is possible to include a CSRF token using JavaScript as I have attempted, or if there is another method that should be used?