Ci sono due passaggi nella configurazione del token CSRF, se si desidera pubblicare senza un modulo.
1) Ottieni il csrftoken
da Cookie.
2) Una volta ottenuto csrftoken, è necessario impostare l'intestazione con csrftoken (prima di inviare POST i dati).
1) Ottenere il csrftoken
da Cookie.
// Function to GET csrftoken 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;
}
var csrftoken = getCookie('csrftoken');
2) Una volta che avete la csrftoken, è necessario impostare l'intestazione con csrftoken (prima di postare i dati).
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// Function to set Request Header with `CSRFTOKEN`
function setRequestHeader(){
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
}
function postSomeData() {
.....
setRequestHeader();
$.ajax({
dataType: 'json',
type: 'POST',
url: "/url-of-some-api/",
data: data,
success: function() {
alert('success');
},
error: function() {
alert('error');
}
});
}
Grazie per la punta con Firebug. Questo l'ha fatto. Potrebbe vedere il Token nel Cookie e quello nella richiesta. Capito che il problema non era in questa parte della mia app. Per rispondere alla mia domanda: il campo del tag modello non è necessario a causa di questa funzione Pre-AJAX. Destra? –
Sì, e se ho capito bene i documenti, Django sta completamente superando il tag del modello, preferendo i cookie per gestire il token CSRF. –