Estoy tratando de usar la biblioteca de búsqueda de JavaScript para enviar un formulario a mi aplicación Django. Sin embargo, no importa lo que haga, todavía se queja de la validación CSRF.
Los documentos sobre Ajax mencionan la especificación de un encabezado que he probado.
También intenté tomar el token de la etiqueta de plantilla y agregarlo a los datos del formulario.
Ningún enfoque parece funcionar.
Aquí está el código básico que incluye tanto el valor del formulario como el encabezado:
let data = new FormData(); data.append('file', file);; data.append('fileName', file.name); // add form input from hidden input elsewhere on the page data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value')); let headers = new Headers(); // add header from cookie const csrftoken = Cookies.get('csrftoken'); headers.append('X-CSRFToken', csrftoken); fetch("/upload/", { method: 'POST', body: data, headers: headers, }) Puedo hacer que esto funcione con JQuery, pero quería intentar usar fetch .
Descubrí esto. El problema es que fetch no incluye cookies por defecto .
La solución simple es agregar credentials: "same-origin" a la solicitud y funciona (con el campo de formulario pero sin los encabezados). Aquí está el código de trabajo:
let data = new FormData(); data.append('file', file);; data.append('fileName', file.name); // add form input from hidden input elsewhere on the page data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value')); fetch("/upload/", { method: 'POST', body: data, credentials: 'same-origin', })Tu pregunta está muy cerca del éxito. Aquí hay una forma json si no desea el método de formulario. Por cierto, el método de formulario de @Cory es muy bueno.
let data = { 'file': file, 'fileName': file.name, }; // You have to download 3rd Cookies library // https://docs.djangoproject.com/en/dev/ref/csrf/#ajax let csrftoken = Cookies.get('csrftoken'); let response = fetch("/upload/", { method: 'POST', body: JSON.stringify(data), headers: { "X-CSRFToken": csrftoken }, })2. Otra forma engorrosa, pero sin ninguna tercera biblioteca.
let data = { 'file': file, 'fileName': file.name, }; let csrftoken = getCookie('csrftoken'); let response = fetch("/upload/", { method: 'POST', body: JSON.stringify(data), headers: { "X-CSRFToken": csrftoken }, }) // The following function are copying from // https://docs.djangoproject.com/en/dev/ref/csrf/#ajax 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 = 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; }