Ajax Post in django template must use form data type to post, otherwise django cannot recognize csrf_token and report CSRF Forbidden.
var send_data = new FormData();
send_data.append("object_id", {{ object_id }});
send_data.append("object_type", '{{ object_type }}');
send_data.append("csrfmiddlewaretoken", '{{ csrf_token }}');
$.ajax({
type: 'POST',
url: '/course/send_certificate/',
data: send_data,
processData: false,
contentType: false,
// dataType: "json",
success: function (data, textStatus, jqXHR) {
$(e.currentTarget).find('div[id="modal-body"]').html(data);
}
})
get csrf token from cookie
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;
}