Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Validación adecuada de Django CSRF usando la solicitud de búsqueda posterior

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 .

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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', })
over 4 years ago · Santiago Trujillo Report

0

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.

  1. Manera ordenada con la tercera biblioteca
 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; }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!